When Scheduling Is Important

If the details of thread scheduling seem somewhat esoteric, here’s the good news: most of the time, all the scheduling details in this chapter have no practical impact on your Java program. This is true, in general, of threaded programs under any operating system and with any threading library, but it’s particularly true in the case of Java programs.

In a Java program, a thread is most often created because the programmer wants to call a method that may block—-usually a read() method on a slow InputStream (such as a SocketInputStream), or the Thread.sleep() method to emulate a periodic timer, or the wait() method to wait for a particular event. As a result, threads in the Java virtual machine tend to oscillate between the blocked and runnable states quite often. And as long as every thread in the Java virtual machine blocks periodically, they will all get an opportunity to run: each thread becomes the currently running thread, blocks, exits the blocked state, is placed on the end of the list for its priority, and moves up through the list as other threads go through the same cycle.

Even in those cases where all the threads in the virtual machine do not periodically block, it’s usually possible to ignore the issue of scheduling altogether. A Java program usually performs a specific task, and often the completion of that task is all that matters. A Java program that is charged with calculating and displaying four convolutions of a GIF image has to wait for ...

Get Java Threads, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.