Java Reference
In-Depth Information
synchronized
(
object
)
{
statements
}
where
object
is the object whose monitor lock will be acquired;
object
is normally
this
if
it's the object in which the
synchronized
statement appears. If several
synchronized
statements in different threads are trying to execute on an object at the same time, only
one of them may be active on the object—all the other threads attempting to enter a
syn-
chronized
statement on the same object are placed in the
blocked
state.
When a
synchronized
statement finishes executing, the object's monitor lock is
released and one of the
blocked
threads attempting to enter a
synchronized
statement can
be allowed to acquire the lock to proceed. Java also allows
synchronized
methods
. Before
executing, a
synchronized
instance method must acquire the lock on the object that's
used to call the method. Similarly, a
static
synchronized
method must acquire the lock
on the class that's used to call the method.
Software Engineering Observation 23.4
Using a
synchronized
block to enforce mutual exclusion is an example of the design
pattern known as the Java Monitor Pattern (see section 4.2.1 of
Java Concurrency in
Practice
by Brian Goetz, et al., Addison-Wesley Professional, 2006).
First, we illustrate the dangers of sharing an object across threads
without
proper synchro-
nization. In this example (Figs. 23.5-23.7), two
Runnable
s maintain references to a single
integer array. Each
Runnable
writes three values to the array, then terminates. This may
seem harmless, but we'll see that it can result in errors if the array is manipulated without
synchronization.
Class
SimpleArray
A
SimpleArray
object (Fig. 23.5) will be
shared
across multiple threads.
SimpleArray
will
enable those threads to place
int
values into
array
(declared at line 9). Line 10 initializes
variable
writeIndex
, which will be used to determine the array element that should be
written to next. The constructor (lines 13-16) creates an integer array of the desired size.
1
// Fig. 23.5: SimpleArray.java
2
// Class that manages an integer array to be shared by multiple threads.
3
import
java.security.SecureRandom;
4
import
java.util.Arrays;
5
6
public class
SimpleArray
// CAUTION: NOT THREAD SAFE!
7
{
8
private static
final
SecureRandom generator =
new
SecureRandom();
9
private final int
[] array;
// the shared integer array
10
private int
writeIndex =
0
;
// shared index of next element to write
11
Fig. 23.5
|
Class that manages an integer array to be shared by multiple threads. (
Caution:
The
example of Figs. 23.5-23.7 is
not
thread safe.) (Part 1 of 2.)