Native Scheduling Support
The Java threading API that we’ve examined so far is somewhat incomplete for certain advanced scheduling uses. For example, there is no way to tell how many CPUs a machine has, or to set the number of LWPs that you want your Solaris virtual machine to have, or to set processor affinity masks so that certain threads run on certain processors. Unfortunately, the only way to overcome these limitations is to introduce native methods calls into your program.
We’ll show just the basic outline of how to do that for certain calls in this section. We’ll give a complete example, but the full details of Windows threads, Solaris or POSIX threads, and the Java native interface ( JNI) are beyond the scope of this book.
We’ll start with a class that allows us to perform three operations: getting the number of CPUs on the machine and getting and setting the number of threads that we want the virtual machine to be able to run concurrently:
public class CPUSupport { static boolean loaded = false; static { try { System.loadLibrary("CPUSupportWin"); loaded = true; } catch (Error e) { try { System.loadLibrary("CPUSupportSolaris"); loaded = true; } catch (Error err) { System.err.println( "Warning: No platform library for CPUSupport"); } } } private static native int getConcurrencyN(); private static native void setConcurrencyN(int i); private static native int getNumProcessorsN(); public static int getConcurrency() { if (!loaded) // Assume green threads. return 1; return getConcurrencyN(); ...
Get Java Threads, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.