Use only 2 CPU cores with Java

Viewed 17180

Is there a way to code Java application to use only 2 CPU cores of the CPU. For example I want to set a limit of the CPU utilization. Is this possible in Java?

4 Answers

If you use a pool of threads and limit the number of threads to 2, no more than 2 cores can be used at the same time. However this is a poor way of limiting CPU usage, and may not even be possible in your scenario (it depends on how many concurrent tasks your application must run).

You can't control this directly. But if you limit the number of threads used to two it will always use only up to two cores.

But note that

a) the actual cores used might vary since the scheduler might move threads from one core to the other

b) there might be other threads started by the JVM (e.g. for garbage collection), that you might not expect from just looking at your application.

You can not assign Threads to cores, therefore you can not do that.

What you can do is to use JNI for such task or use the priority mechanism for Threads.

Related