Java Reference
In-Depth Information
ThreadSafeBankAccount b)
{
source = a;
dest = b;
}
public void run()
{
transfer(250.00);
}
public void transfer(double amount)
{
System.out.println(“Transferring from “ + source.getNumber()
+ “ to “ + dest.getNumber());
ThreadSafeBankAccount first, second;
if(source.getNumber() < dest.getNumber())
{
first = source;
second = dest;
}
else
{
first = dest;
second = source;
}
synchronized(first)
{
Thread.yield();
synchronized(second)
{
System.out.println(“Withdrawing from “
+ source.getNumber());
source.withdraw(amount);
System.out.println(“Depositing into “
+ dest.getNumber());
dest.deposit(amount);
}
}
}
}
Notice in this transfer() method that the code within the critical section did
not change from the LazyTeller class. The difference is in the order the locks
are synchronized. I modified the DeadlockDemo program (in a class named
DeadlockFixedDemo) to use the OrderedTeller instead of the LazyTeller. Fig-
ure 15.12 shows the output. The program runs successfully, does not deadlock,
and the data in the account is correct.
Search WWH ::




Custom Search