Search in sources :

Example 51 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 52 with Synchronization

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

the class InfinispanBatcherTestCase method createNestedBatchClose.

@Test
public void createNestedBatchClose() throws Exception {
    Transaction tx = mock(Transaction.class);
    ArgumentCaptor<Synchronization> capturedSync = ArgumentCaptor.forClass(Synchronization.class);
    when(this.tm.getTransaction()).thenReturn(tx);
    try (TransactionBatch outerBatch = this.batcher.createBatch()) {
        verify(this.tm).begin();
        verify(tx).registerSynchronization(capturedSync.capture());
        reset(this.tm);
        assertSame(tx, outerBatch.getTransaction());
        when(this.tm.getTransaction()).thenReturn(tx);
        try (TransactionBatch innerBatch = this.batcher.createBatch()) {
            verify(this.tm, never()).begin();
            verify(this.tm, never()).suspend();
        }
        verify(tx, never()).rollback();
        verify(tx, never()).commit();
    } finally {
        capturedSync.getValue().afterCompletion(Status.STATUS_COMMITTED);
    }
    verify(tx, never()).rollback();
    verify(tx).commit();
    assertNull(InfinispanBatcher.CURRENT_BATCH.get());
}
Also used : Transaction(javax.transaction.Transaction) Synchronization(javax.transaction.Synchronization) Test(org.junit.Test)

Example 53 with Synchronization

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

the class InfinispanBatcherTestCase method createOverlappingBatchClose.

@SuppressWarnings("resource")
@Test
public void createOverlappingBatchClose() throws Exception {
    Transaction tx = mock(Transaction.class);
    ArgumentCaptor<Synchronization> capturedSync = ArgumentCaptor.forClass(Synchronization.class);
    when(this.tm.getTransaction()).thenReturn(tx);
    TransactionBatch batch = this.batcher.createBatch();
    verify(this.tm).begin();
    verify(tx).registerSynchronization(capturedSync.capture());
    reset(this.tm);
    try {
        assertSame(tx, batch.getTransaction());
        when(this.tm.getTransaction()).thenReturn(tx);
        when(tx.getStatus()).thenReturn(Status.STATUS_ACTIVE);
        try (TransactionBatch innerBatch = this.batcher.createBatch()) {
            verify(this.tm, never()).begin();
            batch.close();
            verify(tx, never()).rollback();
            verify(tx, never()).commit();
        }
    } finally {
        capturedSync.getValue().afterCompletion(Status.STATUS_COMMITTED);
    }
    verify(tx, never()).rollback();
    verify(tx).commit();
    assertNull(InfinispanBatcher.CURRENT_BATCH.get());
}
Also used : Transaction(javax.transaction.Transaction) Synchronization(javax.transaction.Synchronization) Test(org.junit.Test)

Example 54 with Synchronization

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

the class SFSB1 method createEmployeeWaitForTxTimeout.

@TransactionTimeout(value = 1, unit = TimeUnit.SECONDS)
public void createEmployeeWaitForTxTimeout(boolean registerTxSync, String name, String address, int id) {
    LOGGER.trace("org.jboss.as.test.integration.jpa.mockprovider.txtimeout.createEmployeeWaitForTxTimeout " + "entered, will wait for tx time out to occur");
    Employee emp = new Employee();
    emp.setId(id);
    emp.setAddress(address);
    emp.setName(name);
    entityManager.persist(emp);
    boolean done = false;
    if (registerTxSync) {
        transactionSynchronizationRegistry.registerInterposedSynchronization(new Synchronization() {

            @Override
            public void beforeCompletion() {
            }

            @Override
            public void afterCompletion(int status) {
                afterCompletionCalledByTMTimeoutThread = TxUtils.isTransactionManagerTimeoutThread();
            }
        });
    }
    while (!done) {
        try {
            Thread.sleep(250);
            entityManager.find(Employee.class, id);
            int status = transactionSynchronizationRegistry.getTransactionStatus();
            switch(status) {
                case Status.STATUS_COMMITTED:
                    throw new RuntimeException("transaction was committed.");
                case Status.STATUS_ROLLEDBACK:
                    LOGGER.trace("tx timed out and rolled back as expected, success case reached.");
                    done = true;
                    break;
                case Status.STATUS_ACTIVE:
                    LOGGER.trace("tx is still active, sleep for 250ms and check tx status again.");
                    break;
                default:
                    LOGGER.trace("tx status = " + status + ", sleep for 250ms and check tx status again.");
                    break;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            return;
        }
        LOGGER.trace("org.jboss.as.test.integration.jpa.mockprovider.txtimeout.createEmployeeWaitForTxTimeout waiting for tx to timeout");
    }
}
Also used : Synchronization(javax.transaction.Synchronization) TransactionTimeout(org.jboss.ejb3.annotation.TransactionTimeout)

Example 55 with Synchronization

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

the class InfinispanBatcherTestCase method createBatchClose.

@Test
public void createBatchClose() throws Exception {
    Transaction tx = mock(Transaction.class);
    ArgumentCaptor<Synchronization> capturedSync = ArgumentCaptor.forClass(Synchronization.class);
    when(this.tm.getTransaction()).thenReturn(tx);
    try (TransactionBatch batch = this.batcher.createBatch()) {
        verify(this.tm).begin();
        verify(tx).registerSynchronization(capturedSync.capture());
        assertSame(tx, batch.getTransaction());
    } finally {
        capturedSync.getValue().afterCompletion(Status.STATUS_COMMITTED);
    }
    verify(tx).commit();
    assertNull(InfinispanBatcher.CURRENT_BATCH.get());
}
Also used : Transaction(javax.transaction.Transaction) Synchronization(javax.transaction.Synchronization) Test(org.junit.Test)

Aggregations

Synchronization (javax.transaction.Synchronization)87 Test (org.junit.Test)42 Transaction (javax.transaction.Transaction)23 SystemException (javax.transaction.SystemException)21 RollbackException (javax.transaction.RollbackException)14 SQLException (java.sql.SQLException)13 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)7 TransactionSynchronizationRegistry (javax.transaction.TransactionSynchronizationRegistry)7 HeuristicRollbackException (javax.transaction.HeuristicRollbackException)6 ArrayList (java.util.ArrayList)5 HashMap (java.util.HashMap)5 Map (java.util.Map)5 UserTransaction (javax.transaction.UserTransaction)5 XAResource (javax.transaction.xa.XAResource)5 EJBException (javax.ejb.EJBException)4 HeuristicMixedException (javax.transaction.HeuristicMixedException)4 TransactionImple (com.arjuna.ats.internal.jta.transaction.jts.TransactionImple)3 List (java.util.List)3 Xid (javax.transaction.xa.Xid)3 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)3