Java Reference
In-Depth Information
public synchronized void withdraw(double amount)
{
//Method definition
}
When the synchronized withdraw() method is invoked, the current thread
will attempt to obtain the lock on this object and will release this object
when the method is done executing. Synchronizing the entire method is
preferred over synchronizing on the this reference within the method
because it allows the JVM to handle the method call and synchronization
more efficiently. Also, it allows users of the class to see from the method
signature that this method is synchronized.
That being said, do not arbitrarily synchronize methods unless it is
necessary for thread safety, and do not create unnecessary critical
sections. If a method is 50 lines of code, and you need to synchronize only
three lines of it, do not synchronize the entire method. Hanging on to a
lock when it is not needed can have considerable performance side
effects, especially if other threads are waiting for the lock.
I created a new class named ThreadSafeBankAccount that contains this
deposit() method. In addition, I added the synchronized keyword to the with-
draw() method. I also modified the BankTeller class, naming it BankTeller2, so
that it makes a $100 deposit on a ThreadSafeBankAccount object. The follow-
ing SomethingsFixed program is identical to the SomethingsWrong program,
except that it uses the ThreadSafeBankAccount and BankTeller2 classes.
public class SomethingsFixed
{
public static void main(String [] args)
{
ThreadSafeBankAccount account =
new ThreadSafeBankAccount(101, 1000.00);
System.out.println(“Initial balance: $”
+ account.getBalance());
Thread teller1 = new BankTeller2(account);
Thread teller2 = new BankTeller2(account);
teller1.start();
teller2.start();
Thread.yield();
System.out.println(“Withdrawing $200...”);
account.withdraw(200);
System.out.println(“\nFinal balance: $”
+ account.getBalance());
}
}
Search WWH ::




Custom Search