Java 1. 01: Understanding Java threads, Part 3: Thread scheduling and wait/notify. This month, I continue my four- part introduction to Java threads by focusing on thread scheduling, the wait/notify mechanism, and thread interruption. A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions. Refinery planning scheduling energy management optimization emissions management KPIs S-TMS Production and Yield Accounting supply chain gasoline fuels blending petroleum crude oil blending optimization energy performance.
You'll investigate how either a JVM or an operating- system thread scheduler chooses the next thread for execution. As you'll discover, priority is important to a thread scheduler's choice. You'll examine how a thread waits until it receives notification from another thread before it continues execution and learn how to use the wait/notify mechanism for coordinating the execution of two threads in a producer- consumer relationship. Finally, you'll learn how to prematurely awaken either a sleeping or a waiting thread for thread termination or other tasks. I'll also teach you how a thread that is neither sleeping nor waiting detects an interruption request from another thread. Note that this article (part of the Java. World archives) was updated with new code listings and downloadable source code in May 2. Understanding Java threads - read the whole series. Thread scheduling. In an idealized world, all program threads would have their own processors on which to run. Until the time comes when computers have thousands or millions of processors, threads often must share one or more processors. Either the JVM or the underlying platform's operating system deciphers how to share the processor resource among threads—a task known as thread scheduling. That portion of the JVM or operating system that performs thread scheduling is a thread scheduler. Note: To simplify my thread scheduling discussion, I focus on thread scheduling in the context of a single processor. You can extrapolate this discussion to multiple processors; I leave that task to you. Remember two important points about thread scheduling: Java does not force a VM to schedule threads in a specific manner or contain a thread scheduler. That implies platform- dependent thread scheduling. Therefore, you must exercise care when writing a Java program whose behavior depends on how threads are scheduled and must operate consistently across different platforms. Fortunately, when writing Java programs, you need to think about how Java schedules threads only when at least one of your program's threads heavily uses the processor for long time periods and intermediate results of that thread's execution prove important. For example, an applet contains a thread that dynamically creates an image. Periodically, you want the painting thread to draw that image's current contents so the user can see how the image progresses. To ensure that the calculation thread does not monopolize the processor, consider thread scheduling. Examine a program that creates two processor- intensive threads: Listing 1. Sched. Demo. java// Sched. Demo. java. class Sched. Demo. . Depending upon how your JVM implementation schedules threads, you might see output resembling the following: Calc. Thread A: 3. 1. 41. Calc. Thread B: 3. Calc. Thread A: 3. Calc. Thread A: 3. Calc. Thread B: 3. Calc. Thread A: 3. Calc. Thread A: 3. Calc. Thread B: 3. Calc. Thread B: 3. Calc. Thread B: 3. According to the above output, the thread scheduler shares the processor between both threads. However, you could see output similar to this: Calc. Thread A: 3. 1. 41. Calc. Thread A: 3. Calc. Thread A: 3. Calc. Thread A: 3. Calc. Thread A: 3. Calc. Thread B: 3. Calc. Thread B: 3. Calc. Thread B: 3. Calc. Thread B: 3. Calc. Thread B: 3. The above output shows the thread scheduler favoring one thread over another. The two outputs above illustrate two general categories of thread schedulers: green and native. I'll explore their behavioral differences in upcoming sections. While discussing each category, I refer to thread states, of which there are four: Initial state: A program has created a thread's thread object, but the thread does not yet exist because the thread object's start() method has not yet been called. Runnable state: This is a thread's default state. After the call to start() completes, a thread becomes runnable whether or not that thread is running, that is, using the processor. Although many threads might be runnable, only one currently runs. Thread schedulers determine which runnable thread to assign to the processor. Blocked state: When a thread executes the sleep(), wait(), or join() methods, when a thread attempts to read data not yet available from a network, and when a thread waits to acquire a lock, that thread is in the blocked state: it is neither running nor in a position to run. In other words, the thread ceases to exist. How does the thread scheduler choose which runnable thread to run? I begin answering that question while discussing green thread scheduling. I finish the answer while discussing native thread scheduling. Green thread scheduling. Not all operating systems, the ancient Microsoft Windows 3. For such systems, Sun Microsystems can design a JVM that divides its sole thread of execution into multiple threads. The JVM (not the underlying platform's operating system) supplies the threading logic and contains the thread scheduler. JVM threads are green threads, or user threads. A JVM's thread scheduler schedules green threads according to priority—a thread's relative importance, which you express as an integer from a well- defined range of values. Typically, a JVM's thread scheduler chooses the highest- priority thread and allows that thread to run until it either terminates or blocks. At that time, the thread scheduler chooses a thread of the next highest priority. That thread (usually) runs until it terminates or blocks. If, while a thread runs, a thread of higher priority unblocks (perhaps the higher- priority thread's sleep time expired), the thread scheduler preempts, or interrupts, the lower- priority thread and assigns the unblocked higher- priority thread to the processor. Note: A runnable thread with the highest priority will not always run. Here's the Java Language Specification's take on priority: Every thread has a priority. When there is competition for processing resources, threads with higher priority are generally executed in preference to threads with lower priority. Such preference is not, however, a guarantee that the highest priority thread will always be running, and thread priorities cannot be used to reliably implement mutual exclusion. That admission says much about the implementation of green thread JVMs. Those JVMs cannot afford to let threads block because that would tie up the JVM's sole thread of execution. Therefore, when a thread must block, such as when that thread is reading data slow to arrive from a file, the JVM might stop the thread's execution and use a polling mechanism to determine when data arrives. While the thread remains stopped, the JVM's thread scheduler might schedule a lower- priority thread to run. Suppose data arrives while the lower- priority thread is running. Although the higher- priority thread should run as soon as data arrives, that doesn't happen until the JVM next polls the operating system and discovers the arrival. Hence, the lower- priority thread runs even though the higher- priority thread should run. But then Java is not a real- time operating system, so why worry? To understand which runnable green thread becomes the currently running green thread, consider the following. Suppose your application consists of three threads: the main thread that runs the main() method, a calculation thread, and a thread that reads keyboard input. When there is no keyboard input, the reading thread blocks. Assume the reading thread has the highest priority and the calculation thread has the lowest priority. Thread- scheduling diagram for different priority threads. At time T0, the main thread starts running. At time T1, the main thread starts the calculation thread. Because the calculation thread has a lower priority than the main thread, the calculation thread waits for the processor. At time T2, the main thread starts the reading thread. Because the reading thread has a higher priority than the main thread, the main thread waits for the processor while the reading thread runs. At time T3, the reading thread blocks and the main thread runs. At time T4, the reading thread unblocks and runs; the main thread waits. Finally, at time T5, the reading thread blocks and the main thread runs. This alternation in execution between the reading and main threads continues as long as the program runs. The calculation thread never runs because it has the lowest priority and thus starves for processor attention, a situation known as processor starvation. We can alter this scenario by giving the calculation thread the same priority as the main thread. Figure 2 shows the result, beginning with time T2. Thread- scheduling diagram for equal priority main and calculation threads, and a different priority reading thread. At time T2, the reading thread runs while the main and calculation threads wait for the processor. At time T3, the reading thread blocks and the calculation thread runs, because the main thread ran just before the reading thread. At time T4, the reading thread unblocks and runs; the main and calculation threads wait. At time T5, the reading thread blocks and the main thread runs, because the calculation thread ran just before the reading thread. This alternation in execution between the main and calculation threads continues as long as the program runs and depends on the higher- priority thread running and blocking. We must consider one last item in green thread scheduling. What happens when a lower- priority thread holds a lock that a higher- priority thread requires? The higher- priority thread blocks because it cannot get the lock, which implies that the higher- priority thread effectively has the same priority as the lower- priority thread. For example, a priority 6 thread attempts to acquire a lock that a priority 3 thread holds.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. Archives
December 2016
Categories |