Условие. Дописать классы так, чтобы получился перевод денег между двумя счетами в многопоточной среде:
 
public class Account {
 
private final long id;
private BigDecimal balance;
 
 
public Account (long id, BigDecimal balance){
 
if(balance == null || balance.compareTo(BigDecimal.ZERO) < 0){
throw new IllegalArgumentException("Invalid balance");
}
 
this.id = id;
this.balance = balance;
}
 
public long getId(){
return id;
}
 
public synchronized BigDecimal getBalance(){
return balance;
}
 
public synchronized void withdraw(BigDecimal amount){
if(amount == null || amount.compareTo(BigDecimal.ZERO) <= 0){
throw new IllegalArgumentException("Invalid amount");
}
 
if(balance.compareTo(amount) < 0){
throw new IllegalArgumentException("Insufficient funds");
}
 
balance = balance.subtract(amount);
}
 
public synchronized void deposit (BigDecimal amount){
if(amount == null, amount.compareTo(BigDecimal.ZERO) <= 0){
throw new IllegalArgumentException("Invalid amount");
}
balance = balance.add(amount);
 
}
}
public class MoneyTransferService {
 
public void transfer(Account from, Account to, BigDecimal amount){
if(from == null || to == null){
throw new IllegalArgumentException("Invalid account");
}
 
if(from == to || from.getId() == to.getId()){
throw new IllegalArgumentException("Its forbidden to sent for yourself");
}
if(amount == null amount.compareTo(BigDecimal.ZERO) <= 0){
throw new IllegalArgumentException("Invalid Account");
 
}
 
if(from.getId() < to.getId()){
transfer(from,to,from,to,amount);
}
else{
transfer(to,from,from,to,amount)
}
}
 
private void transfer(
Account first,
Account second,
Account from,
Account to,
BigDecimal amount
){
 
synchronized(first){
synchronized(second){
 
from.withdraw(amount);
 
to.deposit(amount);
}
}
}
 
}