Java Reference
In-Depth Information
In Step 1, Task 1 gets the balance from the account. In Step 2, Task 2 gets the same bal-
ance from the account. In Step 3, Task 1 writes a new balance to the account. In Step 4, Task 2
writes a new balance to the account.
The effect of this scenario is that Task 1 does nothing because in Step 4 Task 2 overrides
Task 1's result. Obviously, the problem is that Task 1 and Task 2 are accessing a common
resource in a way that causes a conflict. This is a common problem, known as a race condition ,
in multithreaded programs. A class is said to be thread-safe if an object of the class does not
cause a race condition in the presence of multiple threads. As demonstrated in the preceding
example, the Account class is not thread-safe.
race condition
thread-safe
30.7.1 The synchronized Keyword
To avoid race conditions, it is necessary to prevent more than one thread from simultane-
ously entering a certain part of the program, known as the critical region . The critical region
in Listing 30.4 is the entire deposit method. You can use the keyword synchronized
to synchronize the method so that only one thread can access the method at a time. There
are several ways to correct the problem in Listing 30.4. One approach is to make Account
thread-safe by adding the keyword synchronized in the deposit method in line 38, as
follows:
critical region
public synchronized void deposit( double amount)
A synchronized method acquires a lock before it executes. A lock is a mechanism for exclu-
sive use of a resource. In the case of an instance method, the lock is on the object for which
the method was invoked. In the case of a static method, the lock is on the class. If one thread
invokes a synchronized instance method (respectively, static method) on an object, the lock of
that object (respectively, class) is acquired first, then the method is executed, and finally the
lock is released. Another thread invoking the same method of that object (respectively, class)
is blocked until the lock is released.
With the deposit method synchronized, the preceding scenario cannot happen. If Task 1
enters the method, Task 2 is blocked until Task 1 finishes the method, as shown in FigureĀ 30.12.
Task 1
Task 2
Acquire a lock on the object account
Execute the
deposit
method
Wait to acquire the lock
Release the lock
Acquire a lock on the object account
deposit
Execute the
method
Release the lock
F IGURE 30.12
Task 1 and Task 2 are synchronized.
30.7.2 Synchronizing Statements
Invoking a synchronized instance method of an object acquires a lock on the object, and
invoking a synchronized static method of a class acquires a lock on the class. A synchronized
statement can be used to acquire a lock on any object, not just this object, when executing a
 
 
Search WWH ::




Custom Search