5


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

Ittai
  • 5,625
  • 14
  • 60
  • 97
  • An action should do one thing and one thing only. Why are you doing multiple things such as calling multiple transactions from within one call ? – Romain Hippeau Nov 24 '10 at 02:28
  • The actual scenario is a bit different: It's more of a while(true) loop where inside the thread waits for a file and when it finds one it uses ut.begin,ut.commit. At the end of each such iteration the thread sleeps and so I commit the transaction before the sleep and when it awakes if there is a file then there is a new logical transaction. Of course you could just refactor the code, once a file is found, to another method which grabs the ut and does the logic and commits but the current design is not mine and I just wanted to verify that this is not incorrect. Thanks for your comment though. – Ittai Nov 25 '10 at 07:52

1 Answers1

4

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.