Search in sources :

Example 6 with Synchronization

use of javax.transaction.Synchronization in project graphdb by neo4j-attic.

the class TransactionImpl method doBeforeCompletion.

synchronized void doBeforeCompletion() {
    beforeCompletionRunning = true;
    try {
        for (Synchronization s : syncHooks) {
            try {
                s.beforeCompletion();
            } catch (Throwable t) {
                log.log(Level.WARNING, "Caught exception from tx syncronization[" + s + "] beforeCompletion()", t);
            }
        }
        // execute any hooks added since we entered doBeforeCompletion
        while (!syncHooksAdded.isEmpty()) {
            List<Synchronization> addedHooks = syncHooksAdded;
            syncHooksAdded = new ArrayList<Synchronization>();
            for (Synchronization s : addedHooks) {
                s.beforeCompletion();
                syncHooks.add(s);
            }
        }
    } finally {
        beforeCompletionRunning = false;
    }
}
Also used : Synchronization(javax.transaction.Synchronization)

Example 7 with Synchronization

use of javax.transaction.Synchronization in project hibernate-orm by hibernate.

the class SynchronizationRegistryStandardImplTests method testUserSynchronizationExceptions.

@Test
public void testUserSynchronizationExceptions() {
    // exception in beforeCompletion
    SynchronizationRegistryStandardImpl registry = new SynchronizationRegistryStandardImpl();
    Synchronization synchronization = SynchronizationErrorImpl.forBefore();
    registry.registerSynchronization(synchronization);
    try {
        registry.notifySynchronizationsBeforeTransactionCompletion();
        fail("Expecting LocalSynchronizationException, but call succeeded");
    } catch (LocalSynchronizationException expected) {
    // expected
    } catch (Exception e) {
        fail("Was expecting LocalSynchronizationException, but got " + e.getClass().getName());
    }
    // exception in beforeCompletion
    registry.clearSynchronizations();
    registry = new SynchronizationRegistryStandardImpl();
    synchronization = SynchronizationErrorImpl.forAfter();
    registry.registerSynchronization(synchronization);
    try {
        registry.notifySynchronizationsAfterTransactionCompletion(Status.STATUS_COMMITTED);
        fail("Expecting LocalSynchronizationException, but call succeeded");
    } catch (LocalSynchronizationException expected) {
    // expected
    } catch (Exception e) {
        fail("Was expecting LocalSynchronizationException, but got " + e.getClass().getName());
    }
}
Also used : LocalSynchronizationException(org.hibernate.resource.transaction.LocalSynchronizationException) SynchronizationRegistryStandardImpl(org.hibernate.resource.transaction.internal.SynchronizationRegistryStandardImpl) Synchronization(javax.transaction.Synchronization) LocalSynchronizationException(org.hibernate.resource.transaction.LocalSynchronizationException) NullSynchronizationException(org.hibernate.resource.transaction.NullSynchronizationException) Test(org.junit.Test)

Example 8 with Synchronization

use of javax.transaction.Synchronization in project geode by apache.

the class TXJUnitTest method testJTASynchronization.

@Test
public void testJTASynchronization() throws CacheException, javax.transaction.NotSupportedException, javax.transaction.RollbackException, javax.transaction.SystemException, javax.transaction.HeuristicMixedException, javax.transaction.HeuristicRollbackException {
    javax.transaction.TransactionManager jtaTxMgr = this.cache.getJTATransactionManager();
    TransactionListener tl = new TransactionListener() {

        @Override
        public void afterCommit(TransactionEvent event) {
            ++listenerAfterCommit;
            te = event;
        }

        @Override
        public void afterFailedCommit(TransactionEvent event) {
            ++listenerAfterFailedCommit;
            te = event;
        }

        @Override
        public void afterRollback(TransactionEvent event) {
            ++listenerAfterRollback;
            te = event;
        }

        @Override
        public void close() {
            ++listenerClose;
        }
    };
    this.txMgr.addListener(tl);
    Synchronization gfTXSync;
    // Test successful JTA commit
    jtaTxMgr.begin();
    this.txMgr.begin();
    {
        TXManagerImpl gfTxMgrImpl = (TXManagerImpl) this.txMgr;
        gfTXSync = gfTxMgrImpl.getTXState();
    }
    jtaTxMgr.getTransaction().registerSynchronization(gfTXSync);
    assertEquals(0, this.listenerAfterCommit);
    this.cache.getLogger().info("SWAP:doingCreate");
    this.region.create("syncKey1", "syncVal1");
    jtaTxMgr.commit();
    assertEquals(1, this.listenerAfterCommit);
    assertEquals("syncVal1", this.region.getEntry("syncKey1").getValue());
    try {
        this.txMgr.commit();
        fail("JTA Cache Manager should have called commit!");
    } catch (VirtualMachineError e) {
        SystemFailure.initiateFailure(e);
        throw e;
    } catch (Throwable expected) {
    }
    // Test JTA rollback
    jtaTxMgr.begin();
    this.txMgr.begin();
    {
        TXManagerImpl gfTxMgrImpl = (TXManagerImpl) this.txMgr;
        gfTXSync = gfTxMgrImpl.getTXState();
    }
    jtaTxMgr.getTransaction().registerSynchronization(gfTXSync);
    assertEquals(0, this.listenerAfterRollback);
    this.region.put("syncKey2", "syncVal2");
    jtaTxMgr.rollback();
    assertEquals(1, this.listenerAfterRollback);
    assertTrue(!this.region.containsKey("syncKey2"));
    // Test failed JTA commit with suspend
    jtaTxMgr.begin();
    this.txMgr.begin();
    {
        TXManagerImpl gfTxMgrImpl = (TXManagerImpl) this.txMgr;
        gfTXSync = gfTxMgrImpl.getTXState();
        jtaTxMgr.getTransaction().registerSynchronization(gfTXSync);
        assertEquals(0, this.listenerAfterFailedCommit);
        this.region.put("syncKey3", "syncVal3");
        assertEquals("syncVal3", this.region.getEntry("syncKey3").getValue());
        TXStateProxy gfTx = gfTxMgrImpl.internalSuspend();
        javax.transaction.Transaction jtaTx = jtaTxMgr.suspend();
        assertNull(jtaTxMgr.getTransaction());
        this.region.put("syncKey3", "syncVal4");
        assertEquals("syncVal4", this.region.getEntry("syncKey3").getValue());
        gfTxMgrImpl.internalResume(gfTx);
        try {
            jtaTxMgr.resume(jtaTx);
        } catch (Exception failure) {
            fail("JTA resume failed");
        }
        assertNotNull(jtaTxMgr.getTransaction());
    }
    assertEquals("syncVal3", this.region.getEntry("syncKey3").getValue());
    try {
        jtaTxMgr.commit();
        fail("Expected JTA manager conflict exception!");
    } catch (VirtualMachineError e) {
        SystemFailure.initiateFailure(e);
        throw e;
    } catch (Throwable expected) {
    }
    assertEquals(1, this.listenerAfterFailedCommit);
    assertEquals("syncVal4", this.region.getEntry("syncKey3").getValue());
    // Test failed JTA commit with a new thread
    jtaTxMgr.begin();
    this.txMgr.begin();
    {
        TXManagerImpl gfTxMgrImpl = (TXManagerImpl) this.txMgr;
        gfTXSync = gfTxMgrImpl.getTXState();
        jtaTxMgr.getTransaction().registerSynchronization(gfTXSync);
        assertEquals(1, this.listenerAfterFailedCommit);
        this.region.put("syncKey4", "syncVal3");
        assertEquals("syncVal3", this.region.getEntry("syncKey4").getValue());
        // Create a new thread and have it update the same key, causing
        // a conflict
        final int[] signal = { 0 };
        Thread t = new Thread("non-TX conflict generator") {

            @Override
            public void run() {
                try {
                    region.put("syncKey4", "syncVal4");
                    while (true) synchronized (signal) {
                        signal[0] = 1;
                        signal.notify();
                        signal.wait();
                        if (signal[0] == 0) {
                            break;
                        }
                    }
                } catch (Exception error) {
                    fail("Non-tx thread failure due to: " + error);
                }
            }
        };
        t.start();
        try {
            while (true) synchronized (signal) {
                if (signal[0] == 1) {
                    signal[0] = 0;
                    signal.notify();
                    break;
                } else {
                    signal.wait();
                }
            }
        } catch (InterruptedException dangit) {
            fail("Tx thread waiting for non-tx thread failed due to : " + dangit);
        }
        assertEquals("syncVal3", this.region.getEntry("syncKey4").getValue());
    }
    try {
        jtaTxMgr.commit();
        fail("Expected JTA manager conflict exception!");
    } catch (javax.transaction.HeuristicRollbackException expected) {
    } catch (javax.transaction.RollbackException alsoExpected) {
    } catch (VirtualMachineError e) {
        SystemFailure.initiateFailure(e);
        throw e;
    } catch (Throwable yuk) {
        fail("Did not expect this throwable from JTA commit: " + yuk);
    }
    assertEquals(2, this.listenerAfterFailedCommit);
    assertEquals("syncVal4", this.region.getEntry("syncKey4").getValue());
    this.txMgr.removeListener(tl);
}
Also used : TransactionListener(org.apache.geode.cache.TransactionListener) TXManagerImpl(org.apache.geode.internal.cache.TXManagerImpl) Synchronization(javax.transaction.Synchronization) TimeoutException(org.apache.geode.cache.TimeoutException) EntryExistsException(org.apache.geode.cache.EntryExistsException) EntryNotFoundException(org.apache.geode.cache.EntryNotFoundException) CacheWriterException(org.apache.geode.cache.CacheWriterException) TransactionException(org.apache.geode.cache.TransactionException) CacheLoaderException(org.apache.geode.cache.CacheLoaderException) UnsupportedOperationInTransactionException(org.apache.geode.cache.UnsupportedOperationInTransactionException) FailedSynchronizationException(org.apache.geode.cache.FailedSynchronizationException) NoSuchElementException(java.util.NoSuchElementException) CacheException(org.apache.geode.cache.CacheException) CommitConflictException(org.apache.geode.cache.CommitConflictException) QueryException(org.apache.geode.cache.query.QueryException) TransactionEvent(org.apache.geode.cache.TransactionEvent) TXStateProxy(org.apache.geode.internal.cache.TXStateProxy) Test(org.junit.Test) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Example 9 with Synchronization

use of javax.transaction.Synchronization in project geode by apache.

the class ClientServerTransactionDUnitTest method doJTATx2.

private void doJTATx2(String regionName, CountDownLatch latch1, CountDownLatch latch2) {
    try {
        TransactionManagerImpl tm = TransactionManagerImpl.getTransactionManager();
        UserTransaction utx = new UserTransactionImpl();
        Region r = getClientRegion(regionName);
        utx.begin();
        r.put(key1, "value3");
        TransactionImpl txn = (TransactionImpl) tm.getTransaction();
        Synchronization sync = new SyncImpl();
        txn.registerSynchronization(sync);
        txn.notifyBeforeCompletionForTest();
        latch1.countDown();
        latch2.await();
        utx.rollback();
    } catch (Exception e) {
        latch1.countDown();
        Assert.fail("Unexpected exception while doing JTA Transaction2 ", e);
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) SyncImpl(org.apache.geode.internal.jta.SyncImpl) TransactionManagerImpl(org.apache.geode.internal.jta.TransactionManagerImpl) UserTransactionImpl(org.apache.geode.internal.jta.UserTransactionImpl) UserTransactionImpl(org.apache.geode.internal.jta.UserTransactionImpl) TransactionImpl(org.apache.geode.internal.jta.TransactionImpl) Synchronization(javax.transaction.Synchronization) RollbackException(javax.transaction.RollbackException)

Example 10 with Synchronization

use of javax.transaction.Synchronization in project wildfly by wildfly.

the class JCAOrderedLastSynchronizationList method afterCompletion.

@Override
public void afterCompletion(int status) {
    // https://github.com/jbosstm/narayana/blob/master/ArjunaCore/arjuna/classes/com/arjuna/ats/arjuna/coordinator/TwoPhaseCoordinator.java#L509
    for (int i = preJcaSyncs.size() - 1; i >= 0; --i) {
        Synchronization preJcaSync = preJcaSyncs.get(i);
        if (TransactionLogger.ROOT_LOGGER.isTraceEnabled()) {
            TransactionLogger.ROOT_LOGGER.trace("JCAOrderedLastSynchronizationList.preJcaSyncs.afterCompletion - Class: " + preJcaSync.getClass() + " HashCode: " + preJcaSync.hashCode() + " toString: " + preJcaSync);
        }
        try {
            preJcaSync.afterCompletion(status);
        } catch (Exception e) {
            // Trap these exceptions so the rest of the synchronizations get the chance to complete
            // https://github.com/jbosstm/narayana/blob/5.0.4.Final/ArjunaJTA/jta/classes/com/arjuna/ats/internal/jta/resources/arjunacore/SynchronizationImple.java#L102
            TransactionLogger.ROOT_LOGGER.preJcaSyncAfterCompletionFailed(preJcaSync, tx, e);
        }
    }
    for (int i = jcaSyncs.size() - 1; i >= 0; --i) {
        Synchronization jcaSync = jcaSyncs.get(i);
        if (TransactionLogger.ROOT_LOGGER.isTraceEnabled()) {
            TransactionLogger.ROOT_LOGGER.trace("JCAOrderedLastSynchronizationList.jcaSyncs.afterCompletion - Class: " + jcaSync.getClass() + " HashCode: " + jcaSync.hashCode() + " toString: " + jcaSync);
        }
        try {
            jcaSync.afterCompletion(status);
        } catch (Exception e) {
            // Trap these exceptions so the rest of the synchronizations get the chance to complete
            // https://github.com/jbosstm/narayana/blob/5.0.4.Final/ArjunaJTA/jta/classes/com/arjuna/ats/internal/jta/resources/arjunacore/SynchronizationImple.java#L102
            TransactionLogger.ROOT_LOGGER.jcaSyncAfterCompletionFailed(jcaSync, tx, e);
        }
    }
    if (jcaOrderedLastSynchronizations.remove(tx) == null) {
        // The identifier wasn't stable - scan for it - this can happen in JTS propagation when the UID needs retrieving
        // from the parent and the parent has been deactivated
        Transaction altKey = null;
        Iterator<Entry<Transaction, JCAOrderedLastSynchronizationList>> iterator = jcaOrderedLastSynchronizations.entrySet().iterator();
        while (altKey == null && iterator.hasNext()) {
            Map.Entry<Transaction, JCAOrderedLastSynchronizationList> next = iterator.next();
            if (next.getValue().equals(this)) {
                altKey = next.getKey();
                iterator.remove();
                if (TransactionLogger.ROOT_LOGGER.isTraceEnabled()) {
                    TransactionLogger.ROOT_LOGGER.tracef("Removed: %s [%s]", System.identityHashCode(tx), tx.toString());
                }
                break;
            }
        }
        if (altKey == null) {
            TransactionLogger.ROOT_LOGGER.transactionNotFound(tx);
        }
    }
}
Also used : Entry(java.util.Map.Entry) Transaction(javax.transaction.Transaction) Synchronization(javax.transaction.Synchronization) Map(java.util.Map) SystemException(javax.transaction.SystemException)

Aggregations

Synchronization (javax.transaction.Synchronization)38 Test (org.junit.Test)20 Transaction (javax.transaction.Transaction)10 SQLException (java.sql.SQLException)7 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)7 SystemException (javax.transaction.SystemException)7 RollbackException (javax.transaction.RollbackException)5 TransactionSynchronizationRegistry (javax.transaction.TransactionSynchronizationRegistry)4 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)4 TransactionManager (javax.transaction.TransactionManager)3 UserTransaction (javax.transaction.UserTransaction)3 Map (java.util.Map)2 Set (java.util.Set)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 EJBException (javax.ejb.EJBException)2 ThreadContext (org.apache.openejb.core.ThreadContext)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 NoSuchObjectException (java.rmi.NoSuchObjectException)1 RemoteException (java.rmi.RemoteException)1 Connection (java.sql.Connection)1