I want to make some tuning for multithreaded program.
If I know how much threads can really work in parallel I can make the program much more effective.
Is there
Runtime.getRuntime().availableProcessors();
You can use
Runtime.getRuntime().availableProcessors()
But its more of a best guess and even mentioned by the API
This value may change during a particular invocation of the virtual machine. Applications that are sensitive to the number of available processors should therefore occasionally poll this property and adjust their resource usage appropriately.
Yes on windows for sure. JNA with kernel32.dll. Use SYSTEM_INFO
structure from GetNativeSystemInfo
call. There is dwNumberOfProcessors
among other things.
I believe this will provide the actual number of processors installed, not the number available.
One note about the availableProcessors() method, it does not distinguish between physical cpus and virtual cpus. e.g., if you have hyperthreading enabled on your computer the number will be double the number of physical cpus (which is a little frustrating). unfortunately, there is no way to determine real vs. virtual cpus in pure java.
How about (code snippets speak a 1000 words):
public class Main {
/**
* Displays the number of processors available in the Java Virtual Machine
*/
public void displayAvailableProcessors() {
Runtime runtime = Runtime.getRuntime();
int nrOfProcessors = runtime.availableProcessors();
System.out.println("Number of processors available to the Java Virtual Machine: " + nrOfProcessors);
}
public static void main(String[] args) {
new Main().displayAvailableProcessors();
}
}