In addition to resolving the lock, you can also avoid deadlocks by synchronizing on a locked static lock target before performing any transfer to your account.
class Account{ double balance; int id; private static final Object lock = new Object(); .... public static void transfer(Account from, Account to, double amount){ synchronized(lock) { from.withdraw(amount); to.deposit(amount); } }
This solution has the problem that a private static lock restricts the execution of the system "sequentially".
Another may be if each account has a ReentrantLock:
private final Lock lock = new ReentrantLock(); public static void transfer(Account from, Account to, double amount) { while(true) { if(from.lock.tryLock()){ try { if (to.lock.tryLock()){ try{ from.withdraw(amount); to.deposit(amount); break; } finally { to.lock.unlock(); } } } finally { from.lock.unlock(); } int n = number.nextInt(1000); int TIME = 1000 + n;
There is no deadlock in this approach, since locks are never held indefinitely. If the current lock of the object is obtained, but the second lock is not available, the first lock is released, and the thread falls asleep for a certain time before trying to restore the lock.
dreamcrash Nov 10 '12 at 23:32 2012-11-10 23:32
source share