Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does UserTransaction propagate?

I have a stateless bean with bean-managed transactions, and a method like this:

@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class ... {

    @Resource 
    private UserTransaction ut;
    @EJB 
    private OtherStatelessBeanLocal other;

    public void invokeSomeMethods() 
        ut.begin();
        ...

        // invoke other bean's methods here.
        other.method();

        ...
        ut.commit();

    }

}

So how does the UserTransaction propagate to the OtherStatelessBeanLocal bean?

like image 731
Truong Ha Avatar asked Nov 07 '10 15:11

Truong Ha


2 Answers

The UserTransaction object is an object supplied by the container which wraps access to API calls that the container uses internally, specifically javax.transaction.TransactionManager. The TransactionManager has methods like begin, commit, rollback and javax.transaction.Transaction getTransaction()

Under the covers, the TransactionManager will use a ThreadLocal or similar technique to track the current transaction state with the thread. ThreadLocals are very simple objects that could easily be described as a static HashMap that uses the thread name as the key and an object of your choosing as the value. As long as you stay in the same thread, you can get the object from any point in the invocation chain. This is one of the reasons it is not allowed to start threads in a Java EE environment.

Security propagation works in a similar way, as do JNDI lookups which magically point to the right module's or component's java:comp/env namespace. Bottom line is you cannot implement an app server without ThreadLocals. Propagation sounds more active than it is, when in truth it is simply the act of not leaving the thread so the container and all involved can still find your "stuff".

Back in transaction management terms, the object that a TransactionManager will track in its ThreadLocal will typically implement (directly or indirectly) both the Transaction and TransactionSynchronizationRegistry interfaces. Between these two interfaces, the container has all the hooks it needs to track DataSources, EntityManagers and other resources in the current transaction on your behalf. These interfaces also allow the container to offer callbacks such as SessionSynchronization, as well as means to do other things on your behalf upon transaction completion such as flushing/closing EntityManagers, sending JMS pending messages, and persisting any Timers created by your app in the course of the transaction.

like image 191
David Blevins Avatar answered Nov 09 '22 22:11

David Blevins


Based on EJB specification, you can not pass a transaction context from a bean (in this case your main class ... ) using programmatic transaction into another bean (in this case, other) using programmatic transaction

like image 31
vishy Avatar answered Nov 09 '22 22:11

vishy