Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA Nested Transactions And Locking

Tags:

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?

like image 830
anergy Avatar asked May 24 '12 11:05

anergy


People also ask

What are the rules of committing a nested transaction?

The rules to the usage of a nested transaction are as follows: While the nested (child) transaction is active, the parent transaction may not perform any operations other than to commit or abort, or to create more child transactions. Committing a nested transaction has no effect on the state of the parent transaction.

Can nested transaction be distributed?

A flat or nested transaction that accesses objects handled by different servers is referred to as a distributed transaction.

Does hibernate support nested transactions?

While Hibernate does not explicitly support nested transactions, using a JDBC 3.0 driver that is able to create savepoints can achieve this. Create a Connection at the start of the program when the SessionFactory is created.

Does hibernate lock table during transaction?

Hibernate is not going to do anything to explicitly lock tables you read from. The answer really depends on what Database you're using and what your isolation levels are set to. Locking an entire table by reading rows shouldn't happen in any full featured database written in this century.


2 Answers

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.

like image 125
ewernli Avatar answered Sep 24 '22 18:09

ewernli


Pass the entity and merge...

You can pass your new entity to methodB(), and merge it to the new EntityManager. When the method returns refresh your entity to see the changes:

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(e1);
    entityManager.refresh(e1);
  }
} 

public class Bean_B {
  //Note transaction
  @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
  public void methodB(Entity e1) {
    e1 = entityManager.merge(e1);
    // complex calc to calculate age  
  }

}

Note that this will commit your entity when the new transaction closes after methodB.

...or save it before calling methodB

If you use the method above the entity is saved separately from your main transaction, so you don't loose anything if you save it from Bean_A before calling methodB():

public class Bean_A {
  Bean_B beanB; // Injected or whatever

  @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
  public void createEntity() {
    Entity e1 = // get from db
    e1.setName("Blah");
    entityManager.persist(e1);
  }

  public void methodA() {
    createEntity()   
    int age = beanB.methodB();
  }
} 

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

    // complex calc to calculate age  
  }

}
like image 29
Peter Bagyinszki Avatar answered Sep 22 '22 18:09

Peter Bagyinszki