Java Reference
In-Depth Information
block of the code in a method. This block is referred to as a synchronized block . The general
form of a synchronized statement is as follows:
synchronized block
synchronized (expr) {
statements;
}
The expression expr must evaluate to an object reference. If the object is already locked by
another thread, the thread is blocked until the lock is released. When a lock is obtained on the
object, the statements in the synchronized block are executed and then the lock is released.
Synchronized statements enable you to synchronize part of the code in a method instead
of the entire method. This increases concurrency. You can make Listing 30.4 thread-safe by
placing the statement in line 26 inside a synchronized block:
synchronized (account) {
account.deposit( 1 );
}
Note
Any synchronized instance method can be converted into a synchronized statement.
For example, the following synchronized instance method in (a) is equivalent to (b):
public synchronized void xMethod() {
// method body
public void xMethod() {
synchronized ( this ) {
// method body
}
}
}
(a)
(b)
30.16
Give some examples of possible resource corruption when running multiple threads.
How do you synchronize conflicting threads?
Check
Point
30.17
Suppose you place the statement in line 26 of Listing 30.4 inside a synchronized
block to avoid race conditions, as follows:
synchronized ( this ) {
account.deposit( 1 );
}
Will it work?
30.8 Synchronization Using Locks
Locks and conditions can be explicitly used to synchronize threads.
Key
Point
Recall that in Listing 30.4, 100 tasks deposit a penny to the same account concurrently, which
causes conflicts. To avoid it, you use the synchronized keyword in the deposit method,
as follows:
public synchronized void deposit( double amount)
A synchronized instance method implicitly acquires a lock on the instance before it executes
the method.
Java enables you to acquire locks explicitly, which give you more control for coordinating
threads. A lock is an instance of the Lock interface, which defines the methods for acquiring and
releasing locks, as shown in Figure 30.13. A lock may also use the newCondition() method
to create any number of Condition objects, which can be used for thread communications.
lock
 
 
 
Search WWH ::




Custom Search