Java Reference
In-Depth Information
The Monitor Lock
Every
Object
in Java has an entity called its
monitor lock
(often referred to as the
monitor
or
lock
) that threads use to synchronize access to the data of the object. The monitor lock
of an
Object
has the following features:
A thread uses the
synchronized
keyword to “acquire” an object's lock.
If the lock is available, the thread is said to “own” the lock.
Once the thread leaves the synchronized block of code, the thread “releases” the lock.
If a thread attempts to acquire a lock and the lock is not available, the thread
transitions into the blocked state. The thread remains blocked until the lock becomes
available again.
A thread attempts to acquire a monitor lock on a specifi c object in the following two
ways:
The thread enters a synchronized block of code, in which case the thread attempts to
acquire the monitor lock of the object specified with the
synchronized
keyword.
The thread invokes a
synchronized
method, in which case the thread attempts to
acquire the monitor lock of the object the method is invoked on.
Both of these scenarios involve using the
synchronized
keyword, either at the method
level or on a block of code. Let's look at an example that demonstrates both of these
scenarios, starting with a synchronized block of code.
Synchronized Blocks
Use the
synchronized
keyword to create a synchronized block of code. The syntax is
synchronized(
reference
) {
//synchronized block
}
The
reference
is any
Object
reference, and if the monitor lock of that
Object
is
available, then the thread acquires it; otherwise, the thread blocks until the lock becomes
available.
Let's look at an example. Suppose we have the following class named
BankAccount
:
public class BankAccount {
private double balance;
public void deposit(double amount) {
System.out.println(“Making a deposit: “ + amount);
balance += amount;
Search WWH ::
Custom Search