Search code examples
javatransactionsjtaatomikos

Can I reuse a UserTransaction instance after commit()?



Is the reusage of the ut instance in the following code correct?

UserTransaction ut = (UserTransaction)ctx.lookup("java:comp/UserTransaction");  
ut.begin();  
doSomeWork();  
ut.commit();//Or rollback (I think it doesn't matter)  
ut.begin();   //Or rollback (I think it doesn't matter)  
doOtherWork();  
ut.commit();  

When the JNDI resource is defined so:

Reference atomikosUserTransactionFactoryDS = new Reference("com.atomikos.icatch.jta.UserTransactionImp", 
                "com.atomikos.icatch.jta.UserTransactionFactory", null);
atomikosUserTransactionFactoryDS.add(new RefAddr("name") {  
public Object getContent() {  
        return "UserTransaction";  
}});  
atomikosUserTransactionFactoryDS.add(new RefAddr("type") {  
    public Object getContent() {  
    return "com.atomikos.icatch.jta.UserTransactionImp";  
}});  
initContext.rebind("java:comp/UserTransaction", atomikosUserTransactionFactoryDS);

What I'm not sure about is whether I need to add another lookup, and so to retrieve a new UserTransaction from the factory, before beginning a new UserTransaction?

I don't think it's relevant but as the resource definition states I'm using Atomikos as my Transaction Manager (and so it's factory as the factory).

Thanks,
Ittai


Solution

  • reuse is ok.

    UserTransaction does not represent a specific transaction instance, but rather provides a way of managing the transaction context of the current Thread. Think of it as a singleton if you like. UserTransaction is typically stateless.

    An individual instance of a Transaction is a distinct entity and not normally needed directly by user code. One is created for each tx and can't be reused.

    If you're a hibernate person then think in terms of SessionFactory and Session.