JPA Nested Transactions And Locking

anergy picture anergy · May 24, 2012 · Viewed 21k times · Source

Consider the scenario two methods exists in different stateless bean

public class Bean_A {
   Bean_B beanB; // Injected or whatever
   public void methodA() {
    Entity e1 = // get from db
    e1.setName("Blah");
    entityManager.persist(e1);
    int age = beanB.methodB();

   }
} 
public class Bean_B {
  //Note transaction
  @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
   public void methodB() {

    // complex calc to calculate age  
  }

}

The transaction started by BeanA.methodA would be suspended and new transaction would be started in BeanB.methodB. What if the methodB needs to access same entity that was modified by methodA. This would result in deadlock.Is it possible to prevent it without relying on isolation levels?

Answer

ewernli picture ewernli · May 31, 2012

Hm, let's list all cases.

REQUIRES_NEW does not truely nest transactions, but as you mentioned pauses the current one. There are then simply two transactions accessing the same information. (This is similarly to two regular concurrent transactions, except that they are not concurrent but in the same thread of execution).

T1 T2          T1 T2
―              ―
|              |
               |
   ―           |  ―
   |           |  |
   |     =     |  |
   ―           |  ―
               |
|              |
―              ―

Then we need to consider optimistic vs. pessimistic locking.

Also, we need to consider flushes operated by ORMs. With ORMs, we do not have a clear control when writes occurs, since flush is controlled by the framework. Usually, one implicit flush happens before the commit, but if many entries are modified, the framework can do intermediate flushes as well.

1) Let's consider optimistic locking, where read do not acquire locks, but write acquire exclusive locks.

The read by T1 does not acquire a lock.

1a) If T1 did flush the changes prematurly, it acquired a exclusive lock though. When T2 commits, it attempts to acquire the lock but can't. The system is blocked. This can be though of a particular kind of deadlock. Completion depends on how transactions or locks time out.

1b) If T1 did not flush the changes prematurly, no lock has been acquired. When T2 commits, it acquires and releases it and is sucessful. When T1 attempt to commit, it notices a conflict and fails.

2) Let's consider pessimistic locking, where read acquire shared locks and write exclusive locks.

The read by T1 acquire a shared lock.

2a) If T1 flushed prematurly, it turnes the lock inta an exclusive lock. The situation is similar as 1a)

2b) If T1 did not flush prematurly, T1 holds a shared lock. When T2 commits, it attempts to acquire an exclusive lock and blocks. The system is blocked again.

Conclusion: it's fine with optimistic locking if no premature flushes happen, which you can not stricly control.