我有一个简单的应用程序,操作如下:-
私有无效转移(fromAccount,toAccount,amount){ fromAccount.withdraw(金额);toAccount.deposit(金额);}
如果不在事务上下文中运行,上述实现是非常危险的。如何实现事务,而不使用任何库或@ transaction。
发布于 2019-12-30 11:45:52
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
}
}此解决方案假定撤回检查所请求的金额是否可用,如果没有,则抛出异常。
发布于 2019-12-30 11:52:36
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);
}
}确保您的等于和hashcode返回相同帐号的n个对象的相同值。
https://stackoverflow.com/questions/59529739
复制相似问题