【发布时间】:2023-03-07 20:15:01
【问题描述】:
我遇到了多个线程同时访问某些事务方法的问题
要求是检查一个帐户是否已经存在或以其他方式创建它,下面代码的问题是如果两个线程并行执行具有相同帐户引用的 accountDao.findByAccountRef() 方法,如果他们没有找到该帐户,那么两者尝试创建相同的帐户,这将是一个问题, 谁能给我一些建议如何克服这种情况?
代码贴在下面
谢谢 拉梅什
@Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED)
@Override
public void createAccount(final String accountRef, final Money amount) {
LOG.debug("creating account with reference {}", accountRef);
if (isNotBlank(accountRef)) {
// only create a new Account if it doesn't exist already for the given reference
Optional<AccountEO> accountOptional = accountDao.findByAccountRef(accountRef);
if (accountOptional.isPresent()) {
throw new AccountException("Account already exists for the given reference %s", accountRef);
}
// no such account exists, so create one now
accountDao.create(newAccount(accountRef, neverNull(amount)));
} else {
throw new AccountException("account reference cannot be empty");
}
}
【问题讨论】:
标签: multithreading spring hibernate concurrency spring-transactions