Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 469
Roman Avatar asked Dec 23 '10 23:12

Roman


People also ask

How do you check how many CPU cores you are using?

Through Windows Task Manager: Open Task Manager (press Ctrl+Shift+Esc) Select Performance tab. Look for Cores and Logical Processors (Threads)

Does Java automatically use multiple cores?

Java will benefit from multiple cores, if the OS distribute threads over the available processors. JVM itself do not do anything special to get its threads scheduled evenly across multiple cores.

How do I know how many cores my BIOS has?

Open PowerShell or Command Prompt and enter this command: wmic cpu get NumberOfCores,NumberOfLogicalProcessors. Make sure that there is no space between NumberOfCores and NumberOfLogicalProcessors. The output of the command tells you how many cores and how many logical processors are found on your CPU.

How can you tell how many cpus a physical server has?

Way 2: Check Number of CPU Cores Using System Information Step 1: Press the Windows key + R to open the Run command box, then type msinfo32 and hit Enter. Step 2: Select the Processor tab to see how many cores and logical processors your PC has.


2 Answers

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.

like image 64
John Vint Avatar answered Oct 23 '22 19:10

John Vint


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.

like image 38
jtahlborn Avatar answered Oct 23 '22 19:10

jtahlborn