O'Reilly logo

Java Threads, Second Edition by Henry Wong, Scott Oaks

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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(); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required