22.1 Threads and Concurrency
We first look at some basic concepts before diving into multithreaded programming in Java.
Multitasking
Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between:
- Process-based multitasking
- Thread-based multitasking (associated synonymously with concurrency in Java)
At the coarse-grain level there is process-based multitasking, which allows processes (i.e., programs) to run concurrently on the computer. A familiar example is running a spreadsheet program while also working with a word processor. At the fine-grain level there is thread-based multitasking, which allows parts of the same program to run concurrently on the computer. A familiar example is a word processor that is formatting text as it is typed and is spell-checking at the same time. This is only feasible if the two tasks are performed by two independent paths of execution at runtime. The two tasks would correspond to executing parts of the program code concurrently.
The sequence of code executed for each task defines an independent sequential path of execution within the program, and is called a thread (of execution). Many threads can run concurrently within a program, doing different tasks. At runtime, threads in a program exist in a common memory space, and can therefore share both data and code (i.e., they are lightweight compared to processes). They also share the process running the program.
In a single-threaded environment only one task at a time can be performed. CPU cycles are wasted—for example, when waiting for user input. Multitasking allows idle CPU time to be put to good use.
Some advantages of thread-based multitasking as compared to process-based multitasking are:
- Threads share the same address space—that is, global data is accessible to all threads.
- Context switching between threads—that is, switching of execution from one thread to another—is usually less expensive than between processes.
- The cost of coordination between threads is relatively low.
Java supports thread-based multitasking—that is, concurrency—and provides support for multithreaded programming. Thread-safety is the term used to describe the design of classes that ensure that the state of their objects is always consistent, even when the objects are used concurrently by multiple threads.