I don't think there is any call to get the current CPU currently exposed in the JDK, although it certainly has been previously discussed1 and proposed as a JDK enhancement.
I think until something like that gets implemented your best bet is to use something like JNA (easiest) or JNI (fast) to wrap a native system call like getcpu
on Linux or GetCurrentProcessorNumber
on Windows.
At least on Linux, getcpu
is implemented in the VDSO without a kernel transition, so it should only take a few nanoseconds, plus a few more nanoseconds for the JNI call. JNA is slower.
If you really need speed, you could always add the function as an intrinsic to a bespoke JVM (since OpenJDK is open source). That would shave off several more nanoseconds.
Keep in mind that this information can be out of date as soon as you get it, so you should never rely on it for correctness, only performance. Since you already need to handle getting the "wrong" value, another possible approach is to store the cached value of the CPU ID in a ThreadLocal
, and only update it periodically. This makes slow approaches such as parsing the /proc
filesystem viable since you do them only infrequently. For maximum speed, you can invalidate the thread-local periodically from a timer thread, rather than checking the invalidation condition on each call.
1 Both the discussion and the enhancement request are highly recommended reading.
CoreLocal
or how it was finally solved. – Rosenberry