Search in sources :

Example 21 with Synchronization

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

the class TransactionalTest method tomee2051.

@Test
public void tomee2051() {
    for (int i = 0; i < 2; i++) {
        final AtomicInteger status = new AtomicInteger();
        try {
            bean.tomee2051(new Runnable() {

                @Override
                public void run() {
                    try {
                        OpenEJB.getTransactionManager().getTransaction().registerSynchronization(new Synchronization() {

                            @Override
                            public void beforeCompletion() {
                            // no-op
                            }

                            @Override
                            public void afterCompletion(int state) {
                                status.set(state);
                            }
                        });
                    } catch (final RollbackException | SystemException e) {
                        fail();
                    }
                }
            });
            fail();
        } catch (final AnException e) {
        // no-op
        }
        assertEquals(Status.STATUS_ROLLEDBACK, status.get());
    }
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Synchronization(javax.transaction.Synchronization) Test(org.junit.Test)

Example 22 with Synchronization

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

the class TomcatXADataSourceTest method check.

@Test
public void check() throws SQLException {
    assertNotNull(ds);
    final TomEEDataSourceCreator.TomEEDataSource tds = TomEEDataSourceCreator.TomEEDataSource.class.cast(ManagedDataSource.class.cast(ds).getDelegate());
    // InitSize
    assertEquals(3, tds.getIdle());
    try (final Connection c = ds.getConnection()) {
        assertNotNull(c);
        // just to do something and force the connection init
        final Connection connection = c.getMetaData().getConnection();
        assertThat(connection, instanceOf(JDBCXAConnectionWrapper.class));
    }
    // here we close the connection so we are back in the initial state
    assertEquals(0, tds.getActive());
    assertEquals(3, tds.getIdle());
    for (int it = 0; it < 5; it++) {
        // ensures it always works and not only the first time
        final Collection<Connection> connections = new ArrayList<>(25);
        for (int i = 0; i < 25; i++) {
            final Connection connection = ds.getConnection();
            connections.add(connection);
            // trigger connection retrieving otherwise nothing is done (pool is not used)
            connection.getMetaData();
        }
        assertEquals(25, tds.getActive());
        assertEquals(0, tds.getIdle());
        for (final Connection toClose : connections) {
            toClose.close();
        }
        assertEquals(0, tds.getActive());
        assertEquals(25, tds.getIdle());
    }
    // in tx - closing in tx
    for (int it = 0; it < 5; it++) {
        // ensures it always works and not only the first time
        for (int i = 0; i < 25; i++) {
            tx.run(new Runnable() {

                @Override
                public void run() {
                    try {
                        Connection c = null;
                        for (int i = 0; i < 25; i++) {
                            final Connection connection = ds.getConnection();
                            // trigger connection retrieving otherwise nothing is done (pool is not used)
                            connection.getMetaData();
                            if (c != null) {
                                assertEquals(c, connection);
                            } else {
                                c = connection;
                            }
                        }
                        // ensure we handle properly eager close invocations
                        c.close();
                    } catch (final SQLException sql) {
                        fail(sql.getMessage());
                    }
                }
            });
        }
        assertEquals(0, tds.getActive());
        assertEquals(25, tds.getIdle());
    }
    // in tx - not closing
    for (int it = 0; it < 5; it++) {
        // ensures it always works and not only the first time
        for (int i = 0; i < 25; i++) {
            tx.run(new Runnable() {

                @Override
                public void run() {
                    try {
                        Connection c = null;
                        for (int i = 0; i < 25; i++) {
                            final Connection connection = ds.getConnection();
                            // trigger connection retrieving otherwise nothing is done (pool is not used)
                            connection.getMetaData();
                            if (c != null) {
                                assertEquals(c, connection);
                            } else {
                                c = connection;
                            }
                        }
                    } catch (final SQLException sql) {
                        fail(sql.getMessage());
                    }
                }
            });
        }
        assertEquals(0, tds.getActive());
        assertEquals(25, tds.getIdle());
    }
    // in tx - closing after tx
    for (int it = 0; it < 5; it++) {
        // ensures it always works and not only the first time
        for (int i = 0; i < 25; i++) {
            final AtomicReference<Connection> ref = new AtomicReference<>();
            tx.run(new Runnable() {

                @Override
                public void run() {
                    try {
                        Connection c = null;
                        for (int i = 0; i < 25; i++) {
                            final Connection connection = ds.getConnection();
                            // trigger connection retrieving otherwise nothing is done (pool is not used)
                            connection.getMetaData();
                            if (c != null) {
                                assertEquals(c, connection);
                            } else {
                                c = connection;
                                ref.set(c);
                            }
                        }
                    } catch (final SQLException sql) {
                        fail(sql.getMessage());
                    }
                }
            });
            // closed with tx
            assertTrue(ref.get().isClosed());
            ref.get().close();
            assertTrue(ref.get().isClosed());
        }
        assertEquals(0, tds.getActive());
        assertEquals(25, tds.getIdle());
    }
    // in tx - closing in commit
    for (int it = 0; it < 5; it++) {
        // ensures it always works and not only the first time
        for (int i = 0; i < 25; i++) {
            tx.run(new Runnable() {

                @Override
                public void run() {
                    try {
                        final Connection ref = ds.getConnection();
                        ref.getMetaData();
                        OpenEJB.getTransactionManager().getTransaction().registerSynchronization(new Synchronization() {

                            @Override
                            public void beforeCompletion() {
                            // no-op
                            }

                            @Override
                            public void afterCompletion(final int status) {
                                // JPA does it
                                try {
                                    ref.close();
                                } catch (final SQLException e) {
                                    fail(e.getMessage());
                                }
                            }
                        });
                    } catch (final Exception sql) {
                        fail(sql.getMessage());
                    }
                }
            });
        }
        assertEquals(0, tds.getActive());
        assertEquals(25, tds.getIdle());
    }
    // underlying connection closed when fetch from pool
    for (int it = 0; it < 5; it++) {
        // ensures it always works and not only the first time
        for (int i = 0; i < 25; i++) {
            tx.run(new Runnable() {

                @Override
                public void run() {
                    try {
                        final Connection ref = badDs.getConnection();
                        OpenEJB.getTransactionManager().getTransaction().registerSynchronization(new Synchronization() {

                            @Override
                            public void beforeCompletion() {
                            // no-op
                            }

                            @Override
                            public void afterCompletion(final int status) {
                                // JPA does it
                                try {
                                    ref.close();
                                } catch (final SQLException e) {
                                    fail(e.getMessage());
                                }
                            }
                        });
                        ref.getMetaData();
                    } catch (final Exception sql) {
                    // we expect this
                    }
                }
            });
        }
        assertEquals(0, tds.getActive());
        assertEquals(25, tds.getIdle());
    }
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) XAConnection(javax.sql.XAConnection) ArrayList(java.util.ArrayList) AtomicReference(java.util.concurrent.atomic.AtomicReference) Synchronization(javax.transaction.Synchronization) SQLException(java.sql.SQLException) JDBCXAConnectionWrapper(org.hsqldb.jdbc.pool.JDBCXAConnectionWrapper) Test(org.junit.Test)

Example 23 with Synchronization

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

the class VersionedTest method testStaleRead.

protected ByRef<Object> testStaleRead(BiConsumer<Session, Item> consumer) throws Exception {
    AtomicReference<Exception> synchronizationException = new AtomicReference<>();
    CountDownLatch syncLatch = new CountDownLatch(1);
    CountDownLatch commitLatch = new CountDownLatch(1);
    Future<Boolean> action = executor.submit(() -> withTxSessionApply(s -> {
        try {
            ((SharedSessionContractImplementor) s).getTransactionCoordinator().getLocalSynchronizations().registerSynchronization(new Synchronization() {

                @Override
                public void beforeCompletion() {
                }

                @Override
                public void afterCompletion(int i) {
                    syncLatch.countDown();
                    try {
                        awaitOrThrow(commitLatch);
                    } catch (Exception e) {
                        synchronizationException.set(e);
                    }
                }
            });
            Item item = s.load(Item.class, itemId);
            consumer.accept(s, item);
            s.flush();
        } catch (StaleStateException e) {
            log.info("Exception thrown: ", e);
            markRollbackOnly(s);
            return false;
        } catch (PessimisticLockException e) {
            log.info("Exception thrown: ", e);
            markRollbackOnly(s);
            return false;
        }
        return true;
    }));
    awaitOrThrow(syncLatch);
    ByRef<Object> entryRef = new ByRef<>(null);
    try {
        withTxSession(s -> {
            Item item = s.load(Item.class, itemId);
            assertEquals("Original item", item.getDescription());
            entryRef.set(assertSingleCacheEntry());
        });
    } finally {
        commitLatch.countDown();
    }
    assertTrue(action.get(WAIT_TIMEOUT, TimeUnit.SECONDS));
    assertNull(synchronizationException.get());
    return entryRef;
}
Also used : BaseTransactionalDataRegion(org.hibernate.cache.infinispan.impl.BaseTransactionalDataRegion) Arrays(java.util.Arrays) VersionedEntry(org.hibernate.cache.infinispan.util.VersionedEntry) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Session(org.hibernate.Session) Caches(org.hibernate.cache.infinispan.util.Caches) AtomicReference(java.util.concurrent.atomic.AtomicReference) Future(java.util.concurrent.Future) PessimisticLockException(org.hibernate.PessimisticLockException) InvocationContext(org.infinispan.context.InvocationContext) AdvancedCache(org.infinispan.AdvancedCache) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) Item(org.hibernate.test.cache.infinispan.functional.entities.Item) OtherItem(org.hibernate.test.cache.infinispan.functional.entities.OtherItem) Synchronization(javax.transaction.Synchronization) StaleStateException(org.hibernate.StaleStateException) CyclicBarrier(java.util.concurrent.CyclicBarrier) ByRef(org.infinispan.commons.util.ByRef) Set(java.util.Set) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Assert.assertNotEquals(org.junit.Assert.assertNotEquals) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) BaseCustomInterceptor(org.infinispan.interceptors.base.BaseCustomInterceptor) Assert.assertNull(org.junit.Assert.assertNull) Flag(org.infinispan.context.Flag) Assert.assertFalse(org.junit.Assert.assertFalse) PutKeyValueCommand(org.infinispan.commands.write.PutKeyValueCommand) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) ByRef(org.infinispan.commons.util.ByRef) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) Synchronization(javax.transaction.Synchronization) PessimisticLockException(org.hibernate.PessimisticLockException) StaleStateException(org.hibernate.StaleStateException) PessimisticLockException(org.hibernate.PessimisticLockException) Item(org.hibernate.test.cache.infinispan.functional.entities.Item) OtherItem(org.hibernate.test.cache.infinispan.functional.entities.OtherItem) StaleStateException(org.hibernate.StaleStateException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean)

Example 24 with Synchronization

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

the class XaTransactionImpl method rollback.

public void rollback() throws IllegalStateException, SystemException {
    status = Status.STATUS_ROLLING_BACK;
    runXaResourceRollback();
    status = Status.STATUS_ROLLEDBACK;
    if (connection != null) {
        try {
            connection.rollback();
            connection.close();
        } catch (SQLException sqle) {
            status = Status.STATUS_UNKNOWN;
            throw new SystemException();
        }
    }
    if (synchronizations != null) {
        for (int i = 0; i < synchronizations.size(); i++) {
            Synchronization s = (Synchronization) synchronizations.get(i);
            if (s != null)
                s.afterCompletion(status);
        }
    }
    // status = Status.STATUS_NO_TRANSACTION;
    jtaTransactionManager.endCurrent(this);
}
Also used : SystemException(javax.transaction.SystemException) SQLException(java.sql.SQLException) Synchronization(javax.transaction.Synchronization)

Example 25 with Synchronization

use of javax.transaction.Synchronization in project neo4j-mobile-android by neo4j-contrib.

the class ReadOnlyTransactionImpl method doBeforeCompletion.

synchronized void doBeforeCompletion() {
    beforeCompletionRunning = true;
    try {
        for (Synchronization s : syncHooks) {
            try {
                s.beforeCompletion();
            } catch (Throwable t) {
                log.warning("Caught exception from tx syncronization[" + s + "] beforeCompletion()");
            }
        }
        // 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)

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