Java Syncronization on two objects results in dead lock

59 Views Asked by At

I need to implement some basic money transfer logic between accounts. For the transfer being consistent, I take advantage of syncronization lock.

This is Account object:

class Account {
    UUID id;
    double balance;
}

This is inside transfer worker class:

    public void transfer(Account source, Account target) throws InterruptedException {
        Object firstLock = target.id.compareTo(source.id)  > 0 ? target : source;
        Object secondLock = target.id.compareTo(source.id)  < 0 ? target : source;
        synchronized (firstLock) {
            synchronized (secondLock) {
                // Money tranfer logic
            }   
        }
    }

My question is if source accunt doesn't have enough funds I'm planning to wait that thread until it got funds from other operations. For this one I have waited() for source account. But it ended up with deadlock because target account locks is still on my threds. how can I achive that one ? Can you show me proper way to accomplish this problem ?

This is what I'm trying to postpone money transfer for source accounts which doesn't have

    public void transfer(Account source, Account target) throws InterruptedException {
        Object firstLock = target.id.compareTo(source.id)  > 0 ? target : source;
        Object secondLock = target.id.compareTo(source.id)  < 0 ? target : source;
        synchronized (firstLock) {
            synchronized (secondLock) {
                while(source.balance <= 0 ) {
                    source.wait();
                }
                
                // Money tranfer logic
                
                source.notifyAll();
            }   
        }
    }

Thanks.

0

There are 0 best solutions below