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

做~自己de王妃 提交于 2019-12-04 01:32:45

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. 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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!