Sep 162020

ADM

How to get CPU cores in Java

  • 16 September 2020
  • ADM

 

How to get CPU cores in Java - images/logos/java.jpg

 

Overview

A system may contain multiple physical CPUs (central processing unit), and can contain one or more cores (processors). Also, each core can have multiple threads, usually 2. (Hyper-threading Technology from Intel CPUs).

Example: A system that has 2 dual core CPUs.

2 CPUs x 2 cores per CPU = 4 total cores

You can determine the number of cores available to the Java Virtual Machine by using the static method, availableProcessors from class Runtime. This method is available since Java 1.4. Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running.

Java get the number of cores

public class CPUCores {
    public static void main(String[] args) {
      int processors = Runtime.getRuntime().availableProcessors();
      System.out.println("CPU cores: " + processors);
    }
}

Output

CPU cores: 8

Conclusion

In my case the result is 8 because I tested on a Intel I7 930 CPU with 4 cores and hyper-threading technology.

1 CPU x 4 cores x 2 threads = 8 total cores.

Note that this number is the total number of cores available for your Java application.

 

References