views:

681

answers:

6

Is there a way to find out which processor (either on a single system or mutliple systems) your thread is running on, using Java native threads? If not, is there any library which could help?

A: 

I've never heard of such a call, and I highly doubt there is one, as it's not really necessary, and would require extra platform-specific code.

Matthew Flaschen
+2  A: 

The JVM's thread scheduler is JVM-specific, so there is no 'universal' solution. As far as I know there is nothing available out-of-the-box, but perhaps using:

  • the Sun JVM;
  • Solaris - or Mac, as Tom Hawtin - tackline points out;
  • DTrace.

you might have some luck:

  • trace a thread-start probe, which has as args[3] the "The native/OS thread ID. This is the ID assigned by the host operating system "
  • map the native/OS thread ID to a CPU, using Solaris-specific utilities.
Robert Munteanu
dtrace is also available on Mac OS X (pity the JRE will be behind the times).
Tom Hawtin - tackline
Thanks, updated post.
Robert Munteanu
A: 

As far as I know the standard JDK does not support it (at least up to JDK 6). If that's what you really need, you'll probably need to execute some native calls using JNI. A nice example could be found here (while it's not exactly what you need, I believe it's a good start).

There is a lot of other information you can get from the JDK, by the way, using the ThreadMXBean class (like CPU usage per thread), and maybe you can find what you're looking for there.

Gadi
+1  A: 

Wrong layer of abstraction.

Your program should be concerned about dividing the work it needs to do into threads and submitting them to the JVM for scheduling. How it (the JVM, or the underlying operating system, or whomever for that matter) schedules and which CPU/core your thread ends up running on should not be a factor in program design, at least for a program written for/in an environment like Java.

jeffsix
A: 

The OS will schedule threads on different processors at different times. So even if you get a snapshot of where each thread is running at any given moment, it could be out of date within milli-seconds.

What is the problem you are trying to solve? Perhaps to can do what you want without having to know this.

Peter Lawrey
+1  A: 

The actual processor identity is not relevant, but it can be useful to know whether two threads run on the same core or not in order to optimize concurrent algorithms.

pat