07 January 2007

How many processors am I executing on?

If you're writing threaded code that's meant to be portable, it might behoove you to know how many processors the executing system has.

OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
int numProcessors = osBean.getAvailableProcessors();
System.out.println("Available Processors: " + numProcessors);

You could also interrogate the OperatingSystemMXBean to gather information about architecture that you are executing on. For those not of the faint-of-heart, you could cast the object returned from the getOperatingSystemMXBean call to the VM specific implementation to gather additional goodies. This dangerous assumption would predicate itself on the knowledge of the executing VM though- so probably not a safe bet.

3 comments:

  1. If you just want the number of processors you could use Runtime.availableProcessors()

    ReplyDelete
  2. rummy- no doubt about that. It is probably a simpler (API) to call.

    ReplyDelete