Java Thread Programming

Contents


1

Introduction to Threads

Isn't it nice to be able to read and scroll the text of a Web page while the graphics continue to load? How about having a document in a word processor print in the background while you open another document for editing? Perhaps you've enjoyed writing a response to an email message while another incoming message with a large file attached is quietly downloaded simultaneously? Threads make all this convenient functionality possible by allowing a multi-threaded program to do more than one task at a time. This book helps you learn the skills and techniques necessary to incorporate that kind of useful functionality into your Java programs.

What Is a Thread?

When a modern operating system wants to start running a program, it creates a new process. A process is a program that is currently executing. Every process has at least one thread running within it. Sometimes threads are referred to as lightweight processes . A thread is a path of code execution through a program, and each thread has its own local variables, program counter (pointer to the current instruction being executed), and lifetime. Most modern operating systems allow more than one thread to be running concurrently within a process. When the Java Virtual Machine (JavaVM, or just VM) is started by the operating system, a new process is created. Within that process, many threads can be spawned (created).

When a Java program includes a graphical user interface (GUI), the JavaVM automatically starts even more threads. One of these threads is in charge of delivering GUI events to methods in the program; another is responsible for painting the GUI window.

For example, imagine that a GUI-based program's main thread is performing a complex and long-running calculation and that while this is going on, the user clicks a Stop Calculation button. The GUI event thread would then invoke the event handling code written for this button, allowing the calculation thread to be terminated. If only one thread was present, both of these could not be done simultaneously, and interruption would be difficult.

Why Use Multiple Threads?

In many situations, having more than one thread running in a program is beneficial. Here's a more in-depth look at why this can be good.

Better Interaction with the User

If only one thread was available, a program would be able to do only one thing at a time. In the word processor example, how nice it was to be able to open a second document while the first document was being formatted and queued to the printer. In some older word processors, when the user printed a document, he or she had to wait while the document was prepared for printing and sent to the printer. More modern word processors exploit multiple threads to do these two things at the same time. In a one-processor system, this is actually simulated by the operating system rapidly switching back and forth between two tasks, allowing for better user interaction.

From the perspective of a microprocessor, even the fastest typist takes a tremendous amount of time between keystrokes. In these large gaps of time, the processor can be utilized for other tasks. If one thread is always waiting to give a quick response to a user's actions, such as clicking the mouse or pressing a key, while other threads are off doing other work, the user will perceive better response from the system.

Simulation of Simultaneous Activities

Threads in Java appear to run concurrently, even when only one physical processor exists. The processor runs each thread for a short time and switches among the threads to simulate simultaneous execution. This makes it seem as if each thread has its own processor, creating a virtual multiple processor system. By exploiting this feature, you can make it appear as if multiple tasks are occurring simultaneously when, in fact, each is running for only a brief time before the context is switched to the next thread.

Exploitation of Multiple Processors

In some machines, several real microprocessors are present. If the underlying operating system and the implementation of the JavaVM exploit the use of more than one processor, multi-threaded Java programs can achieve true simultaneous thread execution. A Java program would not have to be modified because it already uses threads as if they were running on different processors simultaneously. It would just be able to run even faster.

Do Other Things While Waiting for Slow I/O Operations

Input and Output (I/O) operations to and from a hard disk or especially across a network are relatively slow when compared to the speed of code execution in the processor. As a result, read/write operations may block for quite a while, waiting to complete.

FIGURE 1.1 The screen layout of the slow network transmission example.

FIGURE 1.2 The partitioning of the work between two threads.

By dividing the work between two threads, the GUI event-handling thread is free to handle other user-generated events. In particular, you might want another button, labeled Cancel Request, that would signal the worker thread to cancel the interaction with the server. If you had not used a worker thread to perform the interaction with the server, but simply had the GUI event thread do the work, the interruption activity triggered by the Cancel Request button would not be possible.

Simplify Object Modeling

Object-oriented analysis of a system before it is built can lead to a design requiring some of the objects to have a thread running within them. This kind of object can be thought of as active, as opposed to passive. A passive object changes its internal state only when one of its methods is invoked. An active object may change its internal state autonomously.

When Multiple Threads Might Not Be Good

It's not always a good idea to add more threads to the design of a program. Threads are not free; they carry some resource overhead.

Each thread also requires processor resources. Overhead is inherent in the scheduling of threads by the operating system. When one thread's execution is suspended and swapped off the processor, and another thread is swapped onto the processor and its execution is resumed, this is called a context switch . CPU cycles are required to do the work of context switching and can become significant if numerous threads are running.

When adding additional threads to the design of a system, these costs should be considered.

Java's Built-in Thread Support

Easy to Start, Tough to Master

It's relatively easy to get started with multi-threaded programming in Java. By building automatic garbage collection into Java, the error-prone work of knowing exactly when the memory for an object can be freed is simplified for developers. Similarly, because threads are an integral part of Java, tasks such as acquiring and releasing a lock on an object are simplified (especially releasing a lock when an unanticipated runtime exception occurs).

Although a Java developer can incorporate multiple threads into his or her program with relative ease, mastering the use of multiple threads and communication among them takes time and knowledge. This book introduces the basics of multi-threaded programming and then moves on to more advanced topics and techniques to help your mastery of Java threads.


Contents

© Copyright 1999, Macmillan Computer Publishing. All rights reserved.