简体   繁体   中英

Is there a way in Java to find out how many CPUs (or cores) are installed?

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 a way in Java to get this info?

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.

One note about the availableProcessors() method, it does not distinguish between physical cpus and virtual cpus. eg, 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.

Runtime.getRuntime().availableProcessors();

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(); 
 }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM