我有一个简单的应用程序,它执行以下操作:-
- 从一个账户提款
- 存入另一个账户
private void transfer(fromAccount,toAccount, amount){ fromAccount.withdraw(amount); toAccount.deposit(amount); }
如果不在事务上下文中运行,上述实现是相当危险的。如何在不使用任何库或@Transactional的情况下实现事务。
public class YourClass() {
private void transfer(fromAccount,toAccount, amount) {
Account fromAccountObj = new Account(fromAccount);
Account toAccountObj = new Account(toAccount);
synchronized(fromAccountObj) {
fromAccount.withdraw(amount);
}
synchronized(toAccountObj) {
toAccount.deposit(amount);
}
}
}
public class Account {
private String accountNumber;
public Account(String accountNumber) {
this.accountNumber = accountNumber;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Account account = (Account) o;
return accountNumber.equals(account.accountNumber);
}
@Override
public int hashCode() {
return Objects.hash(accountNumber);
}
}
确保您的等号和哈希码为相同帐号的 n 个对象返回相同的值
private void transfer(fromAccount,toAccount, amount){
boolean withdrawn = false;
try {
fromAccount.withdraw(amount);
withdrawn = true;
toAccount.deposit(amount);
} catch(Exception e) {
if(withdrawn)
fromAccount.deposit(amount);
// you can throw another Exception here, otherwise you just fail silently
}
}
此解决方案假设提款检查请求的金额是否可用,如果不可用,则引发异常。