Java: XA Transaction propagation within many threads

前端 未结 3 2078
离开以前
离开以前 2021-02-06 16:01

How can I use a transaction manager (such as Bitronix, JBoss TS or Atomikos) in a Java SE (not Java EE or Spring) to support the following use case:

Let\'s assume we hav

相关标签:
3条回答
  • 2021-02-06 16:19

    How about you

    1. BEGIN_TRANSATION: Connect to all 3 databases in your Service,
    2. pass the Connection objects (instead of db object) to MyRunnable
    3. END_TRANSACTION: invoke commit and close on all 3 connections in your Service
    0 讨论(0)
  • 2021-02-06 16:22

    Seems like this can be done using Atomikos using SubTxThread

    //first start a tx
    TransactionManager tm = ...
    tm.begin();
    
    Waiter waiter = new Waiter();
    
    //the code that calls the first EIS; defined by you
    SubTxCode code1 = ...
    
    //the associated thread
    SubTxThread thread1 = new SubTxThread ( waiter , code1 );
    
    //the code that calls the second EIS; defined by you
    SubTxCode code2 = ...
    
    //the associated thread
    SubTxThread thread2 = new SubTxThread ( waiter , code2 );
    
    //start each thread
    thread1.start();
    
    thread2.start();
    
    //wait for completion of all calls
    waiter.waitForAll();
    
    //check result
    if ( waiter.getAbortCount() == 0 ) {
        //no failures -> commit tx
        tm.commit();
    } else {
        tm.rollback();
    }
    
    0 讨论(0)
  • 2021-02-06 16:28

    XA Specification mandates that all XA calls be executed in the same thread context. To elaborate on the reason for this its because the commit could be called before any of the transactional branches are even created in your threads.

    if you are just interested in how to execute those three calls in a XA transaction in JBoss TS

    First make sure your -ds.xml specifies your datasource as an <xa-datasource>

    InitialContext ctx = new InitialContext(parms);
    UserTransaction ut = (UserTransaction) ctx.lookup("java:comp/UserTransaction");
    
    ut.begin();
    
    //Some Transactional Code
    
    ut.commit();
    

    Keep in mind with the code above you would not be able to use the ExecutorService to parallelize the calls.

    Side Note: I don't know a lot about it but JTS/OTS claims to allow multiple threads to share in a transaction. I think it does this by propagating transactional context similar to ws-coordination/ws-transaction and is supported by JBossTS. Could be a red herring, but if your not under a time crunch it might be worth researching.

    0 讨论(0)
提交回复
热议问题