views:

166

answers:

2

Is there a platform independent way to detect the number of physical and/or virtual processors in Java? One potential solution is to detect the operating system and use the Windows environment variable "NUMBER_OF_PROCESSORS". Do Linux and Mac OS X have a similar offering? This however may not be the best solution.

+6  A: 

this may help, from

http://www.javadb.com/get-number-of-available-processors

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html

Runtime runtime = Runtime.getRuntime();
int nrOfProcessors = runtime.availableProcessors();
John Boker
Yes, but note jarnbjo's answer - this does NOT get you the real, physical number of cores or processors in the machine, but just the number of cores or processors available to the JVM. The docs say that this number may even change while the program is running!
Jesper
+2  A: 

Be aware that Runtime#getAvailableProcessors() returns the number of processors available to the Java VM and not the number of processors available to the system (if that matters). E.g. using operating system tools to pin the Java process to a specific processor will usually have immediate effect on the return value, so don't depend on this value to not change during the execution time of a VM.

jarnbjo