I have a problem of accessing some transactional method concurrently by multiple threads
The requirement is to check if an account exists already or otherwise create it, The problem with below code is if two threads parallelly execute the accountDao.findByAccountRef() method with same account reference and if they dont find that account , then both try to create the same account which would be a problem , Could anyone provide me some suggestion how to overcome this situation ?
The code is pasted below
Thanks Ramesh
@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");
}
}