Search code examples
javamysqlspringmultithreadingtransactional

How many transactions do we get when two threads visit a method with @Transactional at the same time?


Let's say that we have this code:

@Transactional
public String getUser(long id) {

    User user = userDao.getUserById(id);
    if(user == null) {
        user = new User();
        user.setXXX(XXX);
        userDao.insert(user);
    }   
}

Assuming that datasource is mysql5:

How many transactions do we get if two threads visit getUser() method at the same time? If the answer is two, then what is the relationship between the two transactions?


Solution

  • As of Spring Documentation:

    The getTransaction(..) method returns a TransactionStatus object, depending on a TransactionDefinition parameter. The returned TransactionStatus might represent a new transaction, or can represent an existing transaction if a matching transaction exists in the current call stack. The implication in this latter case is that, as with Java EE transaction contexts, a TransactionStatus is associated with a thread of execution.

    Which means that for every thread Spring will create a new transaction, unless there is already one existing for that thread.

    When two threads enter this method, two separate transactions are created and there is no relation between them. There is no nesting or anything going here (that is a different scenario). The only case that i can think of where there would be any relation is when the Propagation.REQUIRES_NEW is used, but this is not the case here.