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

前端 未结 5 1397
离开以前
离开以前 2021-02-14 00:46

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

相关标签:
5条回答
  • 2021-02-14 01:22

    Runtime.getRuntime().availableProcessors();

    0 讨论(0)
  • 2021-02-14 01:29

    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.

    0 讨论(0)
  • 2021-02-14 01:39

    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.

    0 讨论(0)
  • 2021-02-14 01:43

    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.

    0 讨论(0)
  • 2021-02-14 01:47

    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(); 
     }
    }
    
    0 讨论(0)
提交回复
热议问题