Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REQUIRES_NEW within REQUIRES_NEW within REQUIRES_NEW ... on and on

JBoss 4.x
EJB 3.0

I've seen code like the following (greatly abbreviated):

@Stateless
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public class EJB1 implements IEJB1
{
   @EJB
   private IEJB1 self;

   @EJB 
   private IEJB2 ejb2;

   @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
   public boolean someMethod1()
   {
     return someMethod2();
   }

   @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
   public boolean someMethod2()
   {
     return self.someMethod3();
   }

   @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
   public boolean someMethod3()
   {
     return ejb2.someMethod1();
   }
}

And say EJB2 is almost an exact copy of EJB1 (same three methods), and EJB2.someMethod3() calls into EJB3.someMethod1(), which then finally in EJB3.someMethod3() writes to the DB.

This is a contrived example, but have seen similar code to the above in our codebase. The code actually works just fine.

However, it feels like terrible practice and I'm concerned about the @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) on every method that doesn't even actually perform any DB writes. Does this actually create a new transaction every single time for every method call with the result of:

new transaction
-new transaction
--new transaction
---new transaction
...(many more)
-------new transaciton (DB write)

And then unwraps at that point? Would this ever be a cause for performance concern? Additional thoughts?

like image 884
Harrison F Avatar asked Dec 04 '22 19:12

Harrison F


1 Answers

Does this actually create a new transaction every single time for every method call

No, it doesn't. The new transaction will be created only when calling method by EJB reference from another bean. Invoking method2 from method1 within the same bean won't spawn the new transaction.

See also here and here. The latter is exceptionally good article, explaining transaction management in EJB.

Edit:
Thanks @korifey for pointing out, that method2 actually calls method3 on bean reference, thus resulting in a new transaction.

like image 178
jFrenetic Avatar answered Dec 28 '22 23:12

jFrenetic