首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在java中实现事务,而不使用任何库(如@ transaction )

在java中实现事务,而不使用任何库(如@ transaction )
EN

Stack Overflow用户
提问于 2019-12-30 11:03:02
回答 2查看 543关注 0票数 0

我有一个简单的应用程序,操作如下:-

  1. 从一个账户中提取
  2. 在另一个账户中的存款

私有无效转移(fromAccount,toAccount,amount){ fromAccount.withdraw(金额);toAccount.deposit(金额);}

如果不在事务上下文中运行,上述实现是非常危险的。如何实现事务,而不使用任何库或@ transaction。

EN

回答 2

Stack Overflow用户

发布于 2019-12-30 11:45:52

代码语言:javascript
复制
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
    }
}

此解决方案假定撤回检查所请求的金额是否可用,如果没有,则抛出异常。

票数 0
EN

Stack Overflow用户

发布于 2019-12-30 11:52:36

代码语言:javascript
复制
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个对象的相同值。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59529739

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档