How do I acquire lock on multiple items?
Consider the example below,
Map<String, Account> accountMap = new HashMap<>(); // key=accountNumber,value=AccountObject
class Account{
private String accountNumber; // getter & setter
private double accountBalance; // getter & setter
}
I need to transfer funds from one account to another, so I was thinking of having a nested synchronized block and realized that it would lead to deadlock.
// bad code
synchronized(accountMap.get(accountNumber1)){
synchronized(accountMap.get(accountNumber2)){
// business logic
}
}
Also, I don't want a single lock because it would block the processing of all the threads for one transaction. Something like below
//bad code
Object mutex = new Object();
synchronized(mutex){
// business logic with accountNumber1 & accountNumber2
}
How do I go about solving this issue? I need to maintain locks only for two account objects.
Also, possible duplicate(but I wanted to know if there are different solutions). Preventing deadlock in a mock banking database