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?
-
If you are doing this for yourself, in windows you can right click a program in the task manager (e.g. the jre), select "set affinity", and you can choose which cores a program is allowed to run on. – Jems Dec 04 '13 at 14:45
-
1http://stackoverflow.com/questions/10487840/java-limiting-resource-usage – benjamin.d Dec 04 '13 at 14:45
-
Which operating system do you use? You can set the CPU affinity of the JVM just like for any other process. – Joni Dec 04 '13 at 14:49
4 Answers
I believe that's something that needs to be handled at the OS level, thus can't be controlled through java code. Take a look at this post. I hope it helps.
Is it possible to force an existing Java application to use no more than x cores?
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).

- 20,627
- 6
- 47
- 86
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.

- 77,657
- 34
- 181
- 348
-
How would you limit the number of threads to two if the JVM itself can use, say, ten internal threads? – NPE Dec 04 '13 at 14:45
-
You can not limit threads and assure that the will be executed on separate cores. – Damian Leszczyński - Vash Dec 04 '13 at 14:46
-
-
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.

- 30,365
- 9
- 60
- 95