Java Reference
In-Depth Information
In a real-world environment in which actual money is involved, this result
would not be acceptable, especially for the customer who appears to have lost
$200. The problem arises because three threads (main() and the two bank
tellers) are accessing the same data in memory at the same time. When work-
ing with data-sensitive information such as a bank account balance, multiple
threads accessing the data should take turns. For example, if a deposit is being
made, no other transactions that affect the balance should be allowed until the
deposit is finished. You can do this by synchronizing your threads, which I
will now discuss.
synchronized Keyword
The BankAccount class from the previous section is clearly not thread-safe.
Multiple threads can make deposits and withdrawals that are not successfully
implemented. To make the class thread-safe, you can take advantage of the
synchronization features built into the Java language.
The synchronized keyword in Java creates a block of code referred to as a
critical section . Every Java object with a critical section of code gets a lock asso-
ciated with the object. To enter a critical section, a thread needs to obtain the
corresponding object's lock.
To fix the problem with the BankAccount class, we need to create a critical
section around the data-sensitive code of the deposit and withdraw methods.
When using the synchronized keyword to create this critical section, you spec-
ify which lock is being requested by passing in a reference to the object that
owns the lock. For example, the following deposit() method synchronizes on
this BankAccount object:
public void deposit(double amount)
{
synchronized(this)
{
double prevBalance = balance;
try
{
Thread.sleep(4000);
}catch(InterruptedException e)
{}
balance = prevBalance + amount;
}
}
The synchronized keyword is commonly used within a class to make a
class thread-safe. In this situation, the critical section is synchronized on
the this reference. An alternate way to synchronize on the this reference is
to declare the entire method as synchronized. For example:
Search WWH ::




Custom Search