Search in sources :

Example 11 with Synchronization

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

the class JCAOrderedLastSynchronizationList method beforeCompletion.

/**
     * Exceptions from Synchronizations that are registered with this TSR are not trapped for before completion. This is because
     * an error in a Sync here should result in the transaction rolling back.
     *
     * You can see that in effect in these classes:
     * https://github.com/jbosstm/narayana/blob/5.0.4.Final/ArjunaCore/arjuna/classes
     * /com/arjuna/ats/arjuna/coordinator/TwoPhaseCoordinator.java#L91
     * https://github.com/jbosstm/narayana/blob/5.0.4.Final/ArjunaJTA
     * /jta/classes/com/arjuna/ats/internal/jta/resources/arjunacore/SynchronizationImple.java#L76
     */
@Override
public void beforeCompletion() {
    // This is needed to guard against syncs being registered during the run, otherwise we could have used an iterator
    int lastIndexProcessed = 0;
    while ((lastIndexProcessed < preJcaSyncs.size())) {
        Synchronization preJcaSync = preJcaSyncs.get(lastIndexProcessed);
        if (TransactionLogger.ROOT_LOGGER.isTraceEnabled()) {
            TransactionLogger.ROOT_LOGGER.trace("JCAOrderedLastSynchronizationList.preJcaSyncs.before_completion - Class: " + preJcaSync.getClass() + " HashCode: " + preJcaSync.hashCode() + " toString: " + preJcaSync);
        }
        preJcaSync.beforeCompletion();
        lastIndexProcessed = lastIndexProcessed + 1;
    }
    // Do the same for the jca syncs
    lastIndexProcessed = 0;
    while ((lastIndexProcessed < jcaSyncs.size())) {
        Synchronization jcaSync = jcaSyncs.get(lastIndexProcessed);
        if (TransactionLogger.ROOT_LOGGER.isTraceEnabled()) {
            TransactionLogger.ROOT_LOGGER.trace("JCAOrderedLastSynchronizationList.jcaSyncs.before_completion - Class: " + jcaSync.getClass() + " HashCode: " + jcaSync.hashCode() + " toString: " + jcaSync);
        }
        jcaSync.beforeCompletion();
        lastIndexProcessed = lastIndexProcessed + 1;
    }
}
Also used : Synchronization(javax.transaction.Synchronization)

Example 12 with Synchronization

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

the class TestWildFlyTSR method test.

@Test
public void test() throws NotSupportedException, SystemException, SecurityException, IllegalStateException, RollbackException, HeuristicMixedException, HeuristicRollbackException {
    jtaPropertyManager.getJTAEnvironmentBean().setTransactionManagerClassName("com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionManagerImple");
    final TransactionSynchronizationRegistry tsr = new TransactionSynchronizationRegistryWrapper(new com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionSynchronizationRegistryImple());
    TransactionManager transactionManager = com.arjuna.ats.jta.TransactionManager.transactionManager();
    transactionManager.begin();
    tsr.registerInterposedSynchronization(new Synchronization() {

        @Override
        public void beforeCompletion() {
            tsr.registerInterposedSynchronization(new Synchronization() {

                @Override
                public void beforeCompletion() {
                    innerSyncCalled = true;
                }

                @Override
                public void afterCompletion(int status) {
                }
            });
        }

        @Override
        public void afterCompletion(int status) {
        }
    });
    transactionManager.commit();
    assertTrue(innerSyncCalled);
}
Also used : TransactionSynchronizationRegistry(javax.transaction.TransactionSynchronizationRegistry) TransactionManager(javax.transaction.TransactionManager) Synchronization(javax.transaction.Synchronization) TransactionSynchronizationRegistryWrapper(org.jboss.as.txn.service.internal.tsr.TransactionSynchronizationRegistryWrapper) Test(org.junit.Test)

Example 13 with Synchronization

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

the class WeldTransactionServices method registerSynchronization.

@Override
public void registerSynchronization(Synchronization synchronizedObserver) {
    try {
        final Synchronization synchronization;
        if (!jtsEnabled) {
            synchronization = synchronizedObserver;
        } else {
            synchronization = new JTSSynchronizationWrapper(synchronizedObserver);
        }
        injectedTransactionManager.getValue().getTransaction().registerSynchronization(synchronization);
    } catch (IllegalStateException e) {
        throw new RuntimeException(e);
    } catch (RollbackException e) {
        throw new RuntimeException(e);
    } catch (SystemException e) {
        throw new RuntimeException(e);
    }
}
Also used : SystemException(javax.transaction.SystemException) Synchronization(javax.transaction.Synchronization) RollbackException(javax.transaction.RollbackException)

Example 14 with Synchronization

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

the class StatefulSessionSynchronizationInterceptor method processInvocation.

@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
    final StatefulSessionComponent component = getComponent(context, StatefulSessionComponent.class);
    final StatefulSessionComponentInstance instance = getComponentInstance(context);
    final OwnableReentrantLock lock = instance.getLock();
    final Object threadLock = instance.getThreadLock();
    final AtomicInteger invocationSyncState = instance.getInvocationSynchState();
    final TransactionSynchronizationRegistry transactionSynchronizationRegistry = component.getTransactionSynchronizationRegistry();
    final Object lockOwner = getLockOwner(transactionSynchronizationRegistry);
    final AccessTimeoutDetails timeout = component.getAccessTimeout(context.getMethod());
    boolean toDiscard = false;
    if (ROOT_LOGGER.isTraceEnabled()) {
        ROOT_LOGGER.trace("Trying to acquire lock: " + lock + " for stateful component instance: " + instance + " during invocation: " + context);
    }
    // we obtain a lock in this synchronization interceptor because the lock needs to be tied to the synchronization
    // so that it can released on the tx synchronization callbacks
    boolean acquired = lock.tryLock(timeout.getValue(), timeout.getTimeUnit(), lockOwner);
    if (!acquired) {
        throw EjbLogger.ROOT_LOGGER.failToObtainLock(component.getComponentName(), timeout.getValue(), timeout.getTimeUnit());
    }
    synchronized (threadLock) {
        //invocation in progress
        invocationSyncState.set(SYNC_STATE_INVOCATION_IN_PROGRESS);
        if (ROOT_LOGGER.isTraceEnabled()) {
            ROOT_LOGGER.trace("Acquired lock: " + lock + " for stateful component instance: " + instance + " during invocation: " + context);
        }
        Object currentTransactionKey = null;
        boolean wasTxSyncRegistered = false;
        try {
            //so enrolling in an existing transaction is not correct
            if (containerManagedTransactions) {
                if (!instance.isSynchronizationRegistered()) {
                    // get the key to current transaction associated with this thread
                    currentTransactionKey = transactionSynchronizationRegistry.getTransactionKey();
                    final int status = transactionSynchronizationRegistry.getTransactionStatus();
                    // if the thread is currently associated with a tx, then register a tx synchronization
                    if (currentTransactionKey != null && status != Status.STATUS_COMMITTED && status != Status.STATUS_ROLLEDBACK) {
                        // register a tx synchronization for this SFSB instance
                        final Synchronization statefulSessionSync = new StatefulSessionSynchronization(instance);
                        transactionSynchronizationRegistry.registerInterposedSynchronization(statefulSessionSync);
                        wasTxSyncRegistered = true;
                        if (ROOT_LOGGER.isTraceEnabled()) {
                            ROOT_LOGGER.trace("Registered tx synchronization: " + statefulSessionSync + " for tx: " + currentTransactionKey + " associated with stateful component instance: " + instance);
                        }
                        // invoke the afterBegin callback on the SFSB
                        instance.afterBegin();
                        instance.setSynchronizationRegistered(true);
                        context.putPrivateData(StatefulTransactionMarker.class, StatefulTransactionMarker.of(true));
                    }
                } else {
                    context.putPrivateData(StatefulTransactionMarker.class, StatefulTransactionMarker.of(false));
                }
            }
            // proceed with the invocation
            try {
                return context.proceed();
            } catch (Exception e) {
                if (component.shouldDiscard(e, context.getMethod())) {
                    toDiscard = true;
                }
                throw e;
            }
        } finally {
            // taken care off by a tx synchronization callbacks.
            if (!wasTxSyncRegistered && !instance.isSynchronizationRegistered()) {
                releaseInstance(instance);
            } else if (!wasTxSyncRegistered) {
                //if we don't release the lock here then it will be acquired multiple times
                //and only released once
                releaseLock(instance);
                //we also call the cache release to decrease the usage count
                if (!instance.isDiscarded()) {
                    instance.getComponent().getCache().release(instance);
                }
            }
            for (; ; ) {
                int state = invocationSyncState.get();
                if (state == SYNC_STATE_INVOCATION_IN_PROGRESS && invocationSyncState.compareAndSet(SYNC_STATE_INVOCATION_IN_PROGRESS, SYNC_STATE_NO_INVOCATION)) {
                    break;
                } else if (state == SYNC_STATE_AFTER_COMPLETE_DELAYED_COMMITTED || state == SYNC_STATE_AFTER_COMPLETE_DELAYED_NO_COMMIT) {
                    try {
                        //invoke the after completion method, other after completion syncs may have already run
                        handleAfterCompletion(state == SYNC_STATE_AFTER_COMPLETE_DELAYED_COMMITTED, instance, toDiscard);
                    } finally {
                        invocationSyncState.set(SYNC_STATE_NO_INVOCATION);
                    }
                } else {
                    EjbLogger.ROOT_LOGGER.unexpectedInvocationState(state);
                    break;
                }
            }
        }
    }
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TransactionSynchronizationRegistry(javax.transaction.TransactionSynchronizationRegistry) OwnableReentrantLock(org.jboss.as.ejb3.tx.OwnableReentrantLock) AccessTimeoutDetails(org.jboss.as.ejb3.concurrency.AccessTimeoutDetails) Synchronization(javax.transaction.Synchronization) EJBException(javax.ejb.EJBException)

Example 15 with Synchronization

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

the class StatefulSessionSynchronizationInterceptorTestCase method testDifferentTx.

/**
     * After the bean is accessed within a tx and the tx has committed, the
     * association should be gone (and thus it is ready for another tx).
     */
@Test
public void testDifferentTx() throws Exception {
    final Interceptor interceptor = new StatefulSessionSynchronizationInterceptor(true);
    final InterceptorContext context = new InterceptorContext();
    context.setInterceptors(Arrays.asList(noop()));
    final StatefulSessionComponent component = mock(StatefulSessionComponent.class);
    context.putPrivateData(Component.class, component);
    when(component.getAccessTimeout(null)).thenReturn(defaultAccessTimeout());
    Cache<SessionID, StatefulSessionComponentInstance> cache = mock(Cache.class);
    when(component.getCache()).thenReturn(cache);
    final TransactionSynchronizationRegistry transactionSynchronizationRegistry = mock(TransactionSynchronizationRegistry.class);
    when(component.getTransactionSynchronizationRegistry()).thenReturn(transactionSynchronizationRegistry);
    when(transactionSynchronizationRegistry.getTransactionKey()).thenReturn("TX1");
    final List<Synchronization> synchronizations = new LinkedList<Synchronization>();
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            Synchronization synchronization = (Synchronization) invocation.getArguments()[0];
            synchronizations.add(synchronization);
            return null;
        }
    }).when(transactionSynchronizationRegistry).registerInterposedSynchronization((Synchronization) any());
    final StatefulSessionComponentInstance instance = new StatefulSessionComponentInstance(component, org.jboss.invocation.Interceptors.getTerminalInterceptor(), Collections.EMPTY_MAP, Collections.emptyMap());
    context.putPrivateData(ComponentInstance.class, instance);
    interceptor.processInvocation(context);
    // commit
    for (Synchronization synchronization : synchronizations) {
        synchronization.beforeCompletion();
    }
    for (Synchronization synchronization : synchronizations) {
        synchronization.afterCompletion(Status.STATUS_COMMITTED);
    }
    synchronizations.clear();
    when(transactionSynchronizationRegistry.getTransactionKey()).thenReturn("TX2");
    interceptor.processInvocation(context);
}
Also used : Synchronization(javax.transaction.Synchronization) LinkedList(java.util.LinkedList) TransactionSynchronizationRegistry(javax.transaction.TransactionSynchronizationRegistry) InvocationOnMock(org.mockito.invocation.InvocationOnMock) InterceptorContext(org.jboss.invocation.InterceptorContext) Interceptor(org.jboss.invocation.Interceptor) SessionID(org.jboss.ejb.client.SessionID) Test(org.junit.Test)

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