Number of processors on a machine

Monday, 23 April 2007, 23:20 | Category : Java, Technology
Tags : ,

How to get Number of processors on a machine in java

public class GetNoOfProcessors
{
public static void main(String[] args)
{
System.out.println(“No. of processors found in the system: ” + getNoOfProcessors());
}
/**
* Gets the no. of processors.
* @return The no. of processors
*/
public static int getNoOfProcessors()
{
int noOfProcessors = 0;
try
{
Runtime runtime = Runtime.getRuntime();
Class runtimeClass = runtime.getClass();
java.lang.reflect.Method availProcessorsMethod = runtimeClass.getMethod(“availableProcessors”, null);
noOfProcessors = ((Integer)availProcessorsMethod.invoke(runtime, null)).intValue();
}
catch (Throwable e)
{
// Ignore this exception as this method is only supported in JDK > 1.4
}
return noOfProcessors;
}
}