Java Reference
In-Depth Information
Chapter 17. Threads and Locks
While most of the discussion in the preceding chapters is concerned only with the behavior
of code as executed a single statement or expression at a time, that is, by a single thread ,
the Java Virtual Machine can support many threads of execution at once. These threads
independently execute code that operates on values and objects residing in a shared main
memory. Threads may be supported by having many hardware processors, by time-slicing a
single hardware processor, or by time-slicing many hardware processors.
Threads are represented by the Thread class. The only way for a user to create a thread is to
create an object of this class; each thread is associated with such an object. A thread will
start when the start() method is invoked on the corresponding Thread object.
The behavior of threads, particularly when not correctly synchronized, can be confusing and
counterintuitive. This chapter describes the semantics of multithreaded programs; it includes
rules for which values may be seen by a read of shared memory that is updated by multiple
threads. As the specification is similar to the memory models for different hardware architec-
tures, these semantics are known as the Java programming language memory model . When
no confusion can arise, we will simply refer to these rules as “the memory model”.
These semantics do not prescribe how a multithreaded program should be executed. Rather,
they describe the behaviors that multithreaded programs are allowed to exhibit. Any execu-
tion strategy that generates only allowed behaviors is an acceptable execution strategy.
17.1. Synchronization
The Java programming language provides multiple mechanisms for communicating between
threads. The most basic of these methods is synchronization , which is implemented using
monitors . Each object in Java is associated with a monitor, which a thread can lock or unlock .
Only one thread at a time may hold a lock on a monitor. Any other threads attempting to lock
that monitor are blocked until they can obtain a lock on that monitor. A thread t may lock a
particular monitor multiple times; each unlock reverses the effect of one lock operation.
The synchronized statement (§ 14.19 ) computes a reference to an object; it then attempts to
perform a lock action on that object's monitor and does not proceed further until the lock
action has successfully completed. After the lock action has been performed, the body of
the synchronized statement is executed. If execution of the body is ever completed, either nor-
mally or abruptly, an unlock action is automatically performed on that same monitor.
Search WWH ::




Custom Search