0

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");
        }
    }

1 Answer 1

1

If you want your system to perform when you have more than a handful of people using it, you can use the concept of Optimistic Locking (I know that there is no lock involved here).

On the creation this works by trying to insert the new account, and if you get an exception because of the duplicate primary key (you'll need to check this from the exception), then you know that the account was already created.

So in short, you optimistically try to create the row and if it fails, you know that there's one already there.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.