Search in sources :

Example 16 with Latch

use of org.mule.runtime.api.util.concurrent.Latch in project mule by mulesoft.

the class CachedConnectionHandlerTestCase method getConnectionConcurrentlyAndConnectOnlyOnce.

@Test
public void getConnectionConcurrentlyAndConnectOnlyOnce() throws Exception {
    Banana mockConnection = mock(Banana.class);
    connectionProvider = mock(ConnectionProvider.class);
    before();
    Latch latch = new Latch();
    when(connectionProvider.connect()).thenAnswer(invocation -> {
        new Thread(() -> {
            try {
                latch.release();
                getConnection();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }).start();
        return mockConnection;
    });
    Banana connection = managedConnection.getConnection();
    assertThat(latch.await(5, TimeUnit.SECONDS), is(true));
    assertThat(connection, is(sameInstance(mockConnection)));
    verify(connectionProvider).connect();
}
Also used : Latch(org.mule.runtime.api.util.concurrent.Latch) Banana(org.mule.tck.testmodels.fruit.Banana) ConnectionProvider(org.mule.runtime.api.connection.ConnectionProvider) Test(org.junit.Test) SmallTest(org.mule.tck.size.SmallTest)

Example 17 with Latch

use of org.mule.runtime.api.util.concurrent.Latch in project mule by mulesoft.

the class PoolingByteBufferManagerTestCase method assertMemoryLimit.

private void assertMemoryLimit(int bufferCapacity, long waitTimeoutMillis) throws InterruptedException {
    ByteBuffer buffer1 = bufferManager.allocate(bufferCapacity);
    ByteBuffer buffer2 = bufferManager.allocate(bufferCapacity);
    assertThat(buffer1.capacity(), is(bufferCapacity));
    assertThat(buffer2.capacity(), is(bufferCapacity));
    Latch latch = new Latch();
    Reference<Boolean> maxMemoryExhausted = new Reference<>(false);
    new Thread(() -> {
        try {
            bufferManager.allocate(bufferCapacity);
            latch.release();
        } catch (Exception e) {
            maxMemoryExhausted.set(e.getCause() instanceof MaxStreamingMemoryExceededException);
        }
    }).start();
    assertThat(latch.await(waitTimeoutMillis * 2, MILLISECONDS), is(false));
    assertThat(maxMemoryExhausted.get(), is(true));
    bufferManager.deallocate(buffer1);
    Latch secondLatch = new Latch();
    new Thread(() -> {
        try {
            bufferManager.allocate(bufferCapacity);
            maxMemoryExhausted.set(false);
        } finally {
            secondLatch.release();
        }
    }).start();
    assertThat(secondLatch.await(waitTimeoutMillis, MILLISECONDS), is(true));
    assertThat(maxMemoryExhausted.get(), is(false));
}
Also used : Reference(org.mule.runtime.api.util.Reference) Latch(org.mule.runtime.api.util.concurrent.Latch) ByteBuffer(java.nio.ByteBuffer) ExpectedException(org.junit.rules.ExpectedException)

Example 18 with Latch

use of org.mule.runtime.api.util.concurrent.Latch in project mule by mulesoft.

the class AsyncRequestReplyRequesterTestCase method returnsNullWhenInterruptedWhileWaitingForReply.

@Test
@Ignore("See MULE-8830")
public void returnsNullWhenInterruptedWhileWaitingForReply() throws Exception {
    final Latch fakeLatch = new Latch() {

        @Override
        public void await() throws InterruptedException {
            throw new InterruptedException();
        }
    };
    asyncReplyMP = new TestAsyncRequestReplyRequester(muleContext) {

        @Override
        protected Latch createEventLock() {
            return fakeLatch;
        }
    };
    final CountDownLatch processingLatch = new CountDownLatch(1);
    Processor target = mock(Processor.class);
    asyncReplyMP.setListener(target);
    MessageSource messageSource = mock(MessageSource.class);
    asyncReplyMP.setReplySource(messageSource);
    asyncReplyMP.setMuleContext(muleContext);
    final boolean[] exceptionThrown = new boolean[1];
    final Object[] responseEvent = new Object[1];
    Thread thread = new Thread(() -> {
        try {
            responseEvent[0] = asyncReplyMP.process(testEvent());
        } catch (MuleException e) {
            exceptionThrown[0] = true;
        } finally {
            processingLatch.countDown();
        }
    });
    thread.start();
    assertTrue(processingLatch.await(RECEIVE_TIMEOUT, TimeUnit.MILLISECONDS));
    assertFalse(exceptionThrown[0]);
    assertNull(responseEvent[0]);
}
Also used : SensingNullMessageProcessor(org.mule.tck.SensingNullMessageProcessor) Processor(org.mule.runtime.core.api.processor.Processor) AsyncDelegateMessageProcessor(org.mule.runtime.core.internal.processor.AsyncDelegateMessageProcessor) CountDownLatch(java.util.concurrent.CountDownLatch) Latch(org.mule.runtime.api.util.concurrent.Latch) MessageSource(org.mule.runtime.core.api.source.MessageSource) CountDownLatch(java.util.concurrent.CountDownLatch) MuleException(org.mule.runtime.api.exception.MuleException) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 19 with Latch

use of org.mule.runtime.api.util.concurrent.Latch in project mule by mulesoft.

the class AbstractAsyncRequestReplyRequester method receiveAsyncReply.

private PrivilegedEvent receiveAsyncReply(CoreEvent event) throws MuleException {
    String asyncReplyCorrelationId = getAsyncReplyCorrelationId(event);
    System.out.println("receiveAsyncReply: " + asyncReplyCorrelationId);
    Latch asyncReplyLatch = getLatch(asyncReplyCorrelationId);
    // flag for catching the interrupted status of the Thread waiting for a
    // result
    boolean interruptedWhileWaiting = false;
    boolean resultAvailable = false;
    PrivilegedEvent result;
    try {
        if (logger.isDebugEnabled()) {
            logger.debug("Waiting for async reply message with id: " + asyncReplyCorrelationId);
        }
        // how long should we wait for the lock?
        if (timeout <= 0) {
            asyncReplyLatch.await();
            resultAvailable = true;
        } else {
            resultAvailable = asyncReplyLatch.await(timeout, MILLISECONDS);
        }
        if (!resultAvailable) {
            asyncReplyLatch.await(1000, MILLISECONDS);
            resultAvailable = asyncReplyLatch.getCount() == 0;
        }
    } catch (InterruptedException e) {
        interruptedWhileWaiting = true;
    } finally {
        locks.remove(asyncReplyCorrelationId);
        result = responseEvents.remove(asyncReplyCorrelationId);
        if (interruptedWhileWaiting) {
            Thread.currentThread().interrupt();
            return null;
        }
    }
    if (resultAvailable) {
        if (result == null) {
            // this should never happen, just using it as a safe guard for now
            throw new IllegalStateException("Response MuleEvent is null");
        }
        // Copy event because the async-reply message was received by a different
        // receiver thread (or the senders dispatcher thread in case of vm
        // with queueEvents="false") and the current thread may need to mutate
        // the even. See MULE-4370
        setCurrentEvent(result);
        return result;
    } else {
        addProcessed(new ProcessedEvents(asyncReplyCorrelationId, EndReason.FINISHED_BY_TIMEOUT));
        if (failOnTimeout) {
            notificationFirer.dispatch(new RoutingNotification(event.getMessage(), null, ASYNC_REPLY_TIMEOUT));
            throw new ResponseTimeoutException(responseTimedOutWaitingForId((int) timeout, asyncReplyCorrelationId), null);
        } else {
            return null;
        }
    }
}
Also used : ResponseTimeoutException(org.mule.runtime.core.privileged.routing.ResponseTimeoutException) PrivilegedEvent(org.mule.runtime.core.privileged.event.PrivilegedEvent) Latch(org.mule.runtime.api.util.concurrent.Latch) RoutingNotification(org.mule.runtime.api.notification.RoutingNotification)

Example 20 with Latch

use of org.mule.runtime.api.util.concurrent.Latch in project mule by mulesoft.

the class WaitComponent method reset.

public static void reset() {
    componentInitializedLatch = new Latch();
    waitLatch = new Latch();
}
Also used : Latch(org.mule.runtime.api.util.concurrent.Latch)

Aggregations

Latch (org.mule.runtime.api.util.concurrent.Latch)24 Test (org.junit.Test)17 Queue (org.mule.runtime.core.api.util.queue.Queue)7 QueueManager (org.mule.runtime.core.api.util.queue.QueueManager)7 QueueSession (org.mule.runtime.core.api.util.queue.QueueSession)7 AbstractQueueManager (org.mule.runtime.core.internal.util.queue.AbstractQueueManager)7 Description (io.qameta.allure.Description)3 List (java.util.List)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 MILLISECONDS (java.util.concurrent.TimeUnit.MILLISECONDS)3 AtomicReference (java.util.concurrent.atomic.AtomicReference)3 Consumer (java.util.function.Consumer)3 Serializable (java.io.Serializable)2 CompletableFuture (java.util.concurrent.CompletableFuture)2 TimeoutException (java.util.concurrent.TimeoutException)2 Assert.assertThat (org.junit.Assert.assertThat)2 ExpectedException (org.junit.rules.ExpectedException)2 MuleException (org.mule.runtime.api.exception.MuleException)2 Reference (org.mule.runtime.api.util.Reference)2 DefaultQueueConfiguration (org.mule.runtime.core.api.util.queue.DefaultQueueConfiguration)2