Can I set the number of Threads/CPUs available to the Java VM? Can I set the number of Threads/CPUs available to the Java VM? multithreading multithreading

Can I set the number of Threads/CPUs available to the Java VM?


The problem of CPU limits in JVM was solved in Java 10 and is backported to Java 8 from build 8u191:

-XX:ActiveProcessorCount=2


If you're on linux simply wrap the java launcher in a numactl / taskset command. That allows the JVM to spawn any number of threads but schedules them on a fixed amount of physical cores.

Similar tools are available for other OSes too.


Try to run your program with "affinity" for windows user.

For Example: instead of running "java Test", you should run:"start /affinity 1 java Test" when you need 1 core;"start /affinity 3 java Test" when you need 2 core;....The parameter used should follow this form:

https://blogs.msdn.microsoft.com/santhoshonline/2011/11/24/how-to-launch-a-process-with-cpu-affinity-set/

You can use "System.out.println(Runtime.getRuntime().availableProcessors()); to check.