Java Code Examples for org.eclipse.microprofile.faulttolerance.exceptions.TimeoutException

The following examples show how to use org.eclipse.microprofile.faulttolerance.exceptions.TimeoutException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Test
public void delayed_value_timedOut() throws InterruptedException {
    Barrier invocationDelayBarrier = Barrier.interruptible();

    TestInvocation<Future<String>> invocation = TestInvocation.delayed(invocationDelayBarrier,
            () -> completedFuture("foobar"));
    Timeout<Future<String>> timeout = new Timeout<>(invocation, "test invocation", 1000,
            timeoutWatcher, null);
    TestThread<Future<String>> testThread = runOnTestThread(new AsyncTimeout<>(timeout, asyncExecutor));
    watcherTimeoutElapsedBarrier.open();
    watcherExecutionInterruptedBarrier.await();

    assertThatThrownBy(testThread::await)
            .isExactlyInstanceOf(TimeoutException.class)
            .hasMessage("test invocation timed out");
    assertThat(timeoutWatcher.timeoutWatchWasCancelled()).isFalse();
}
 
Example 2
@Test
public void delayed_value_timedOutNoninterruptibly() throws InterruptedException {
    Barrier invocationDelayBarrier = Barrier.noninterruptible();

    TestInvocation<Future<String>> invocation = TestInvocation.delayed(invocationDelayBarrier,
            () -> completedFuture("foobar"));

    Timeout<Future<String>> timeout = new Timeout<>(invocation, "test invocation", 1000,
            timeoutWatcher, null);
    TestThread<Future<String>> testThread = runOnTestThread(new AsyncTimeout<>(timeout, asyncExecutor));
    watcherTimeoutElapsedBarrier.open();
    watcherExecutionInterruptedBarrier.await();

    assertThatThrownBy(testThread::await)
            .isExactlyInstanceOf(TimeoutException.class)
            .hasMessage("test invocation timed out");
    assertThat(timeoutWatcher.timeoutWatchWasCancelled()).isFalse(); // watcher should not be canceled if it caused the stop

    invocationDelayBarrier.open();
}
 
Example 3
@Test
public void delayed_value_timedOut() throws Exception {
    Barrier invocationDelayBarrier = Barrier.interruptible();

    TestInvocation<CompletionStage<String>> invocation = TestInvocation.delayed(invocationDelayBarrier,
            () -> completedStage("foobar"));
    TestThread<CompletionStage<String>> result = runOnTestThread(new CompletionStageTimeout<>(invocation,
            "test invocation", 1000, timeoutWatcher, timeoutActionExecutor, null, true));
    watcherTimeoutElapsedBarrier.open();
    watcherExecutionInterruptedBarrier.await();
    assertThatThrownBy(result.await().toCompletableFuture()::get)
            .isExactlyInstanceOf(ExecutionException.class)
            .hasCauseExactlyInstanceOf(TimeoutException.class)
            .hasMessageContaining("test invocation timed out");
    assertThat(timeoutWatcher.timeoutWatchWasCancelled()).isFalse();
}
 
Example 4
@Test
public void delayed_value_timedOutNoninterruptibly() throws Exception {
    Barrier invocationDelayBarrier = Barrier.noninterruptible();

    TestInvocation<CompletionStage<String>> invocation = TestInvocation.delayed(invocationDelayBarrier,
            () -> completedStage("foobar"));
    TestThread<CompletionStage<String>> result = runOnTestThread(new CompletionStageTimeout<>(invocation,
            "test invocation", 1000, timeoutWatcher, timeoutActionExecutor, null, true));
    watcherTimeoutElapsedBarrier.open();
    watcherExecutionInterruptedBarrier.await();
    invocationDelayBarrier.open();
    assertThatThrownBy(result.await().toCompletableFuture()::get)
            .isExactlyInstanceOf(ExecutionException.class)
            .hasCauseExactlyInstanceOf(TimeoutException.class)
            .hasMessageContaining("test invocation timed out");
    assertThat(timeoutWatcher.timeoutWatchWasCancelled()).isFalse();
}
 
Example 5
@Test
public void delayed_exception_timedOut() throws Exception {
    Barrier invocationDelayBarrier = Barrier.interruptible();

    TestInvocation<CompletionStage<Void>> invocation = TestInvocation.delayed(invocationDelayBarrier,
            () -> failedStage(new TestException()));
    TestThread<CompletionStage<Void>> result = runOnTestThread(new CompletionStageTimeout<>(invocation,
            "test invocation", 1000, timeoutWatcher, timeoutActionExecutor, null, true));
    watcherTimeoutElapsedBarrier.open();
    watcherExecutionInterruptedBarrier.await();
    assertThatThrownBy(result.await().toCompletableFuture()::get)
            .isExactlyInstanceOf(ExecutionException.class)
            .hasCauseExactlyInstanceOf(TimeoutException.class)
            .hasMessageContaining("test invocation timed out");
    assertThat(timeoutWatcher.timeoutWatchWasCancelled()).isFalse();
}
 
Example 6
@Test
public void delayed_exception_timedOutNoninterruptibly() throws Exception {
    Barrier invocationDelayBarrier = Barrier.noninterruptible();

    TestInvocation<CompletionStage<Void>> invocation = TestInvocation.delayed(invocationDelayBarrier,
            () -> failedStage(new TestException()));
    TestThread<CompletionStage<Void>> result = runOnTestThread(new CompletionStageTimeout<>(invocation,
            "test invocation", 1000, timeoutWatcher, timeoutActionExecutor, null, true));
    watcherTimeoutElapsedBarrier.open();
    watcherExecutionInterruptedBarrier.await();
    invocationDelayBarrier.open();
    assertThatThrownBy(result.await().toCompletableFuture()::get)
            .isExactlyInstanceOf(ExecutionException.class)
            .hasCauseExactlyInstanceOf(TimeoutException.class)
            .hasMessageContaining("test invocation timed out");
    assertThat(timeoutWatcher.timeoutWatchWasCancelled()).isFalse();
}
 
Example 7
@Test
public void immediatelyReturning_completionStageTimedOut() throws Exception {
    Barrier barrier = Barrier.interruptible();

    TestInvocation<CompletionStage<Void>> invocation = TestInvocation.immediatelyReturning(
            () -> CompletableFuture.supplyAsync(() -> {
                try {
                    barrier.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException("interrupted");
                }
                return null;
            }));
    TestThread<CompletionStage<Void>> result = runOnTestThread(new CompletionStageTimeout<>(invocation,
            "test invocation", 1000, timeoutWatcher, timeoutActionExecutor, null, true));
    watcherTimeoutElapsedBarrier.open();
    watcherExecutionInterruptedBarrier.await();
    assertThatThrownBy(result.await().toCompletableFuture()::get)
            .isExactlyInstanceOf(ExecutionException.class)
            .hasCauseExactlyInstanceOf(TimeoutException.class);
    barrier.open();
}
 
Example 8
/**
 * Configured to always time out and Retry until CircuitBreaker is triggered on 4th call. Runs asynchronously.
 */
@CircuitBreaker(successThreshold = 2, requestVolumeThreshold = 4, failureRatio = 0.75, delay = 50000)
@Retry(retryOn = {TestException.class, TimeoutException.class}, maxRetries = 7, maxDuration = 20000)
@Timeout(100) // Scaled via config
@Asynchronous
public Future<Connection> serviceC() {
    Connection conn = null;
    counterForInvokingServiceC++;

    try {
        Thread.sleep(TCKConfig.getConfig().getTimeoutInMillis(5000));
        throw new RuntimeException("Timeout did not interrupt");
    } 
    catch (InterruptedException e) {
        //expected
    }
    return CompletableFuture.completedFuture(conn);
}
 
Example 9
/**
 * Configured to always time out and Retry until CircuitBreaker is triggered on 4th call.
 */
@CircuitBreaker(successThreshold = 2, requestVolumeThreshold = 4, failureRatio = 0.75, delay = 50000)
@Retry(retryOn = {RuntimeException.class, TimeoutException.class}, maxRetries = 7, maxDuration = 20000)
@Timeout(100) // Scaled via config
public Connection serviceC() {
    Connection conn = null;
    counterForInvokingServiceC++;

    try {
        Thread.sleep(TCKConfig.getConfig().getTimeoutInMillis(5000));
        throw new RuntimeException("Timeout did not interrupt");
    } 
    catch (InterruptedException e) {
        //expected
    }
    return conn;
}
 
Example 10
@Test
public void testTimeoutAsync() throws Exception {
    CompletableFuture<Void> waitingFuture = newWaitingFuture();
    CompletableFuture<Void> completionFuture = new CompletableFuture<Void>();

    long startTime = System.nanoTime();
    Future<Void> result = client.serviceTimeoutAsync(waitingFuture, completionFuture);
    expect(TimeoutException.class, result);
    long resultTime = System.nanoTime();
    
    // We should get the TimeoutException after 500ms, allow up to 1500ms
    assertThat("Time for result to be complete", Duration.ofNanos(resultTime - startTime), lessThan(config.getTimeoutInDuration(1500)));

    assertFalse(completionFuture.isDone(), "Method should still be running");

    // If we release the waitingFuture, the method should quickly complete
    waitingFuture.complete(null);
    completionFuture.get(config.getTimeoutInMillis(5000), TimeUnit.MILLISECONDS);
}
 
Example 11
@Test
public void testTimeoutAsyncCS() throws InterruptedException {
    AtomicBoolean wasInterrupted = new AtomicBoolean(false);
    CompletableFuture<Void> completionFuture = new CompletableFuture<>();
    AtomicLong endTime = new AtomicLong();
    
    long startTime = System.nanoTime();
    client.serviceTimeoutAsyncCS(config.getTimeoutInMillis(4000))
          .thenRun(() -> completionFuture.complete(null))
          .exceptionally((e) -> {
              completionFuture.completeExceptionally(e);
              return null;
          })
          .thenRun(() -> endTime.set(System.nanoTime()))
          .thenRun(() -> wasInterrupted.set(Thread.interrupted()));
    
    expect(TimeoutException.class, completionFuture);
    
    // Interrupt flag should not be set
    assertFalse(wasInterrupted.get(), "Thread was still interrupted when thenRun steps were run");
    
    // Expect that the method will timeout after 500ms, allow up to 1500ms
    assertThat("Execution time", Duration.ofNanos(endTime.get() - startTime), lessThan(config.getTimeoutInDuration(1500)));

}
 
Example 12
@Test
public void testTimeoutAsyncRetry() {
    CompletableFuture<?> waitingFuture = newWaitingFuture();

    // Expect to run method three times, each one timing out after 500ms
    long startTime = System.nanoTime();
    Future<Void> result = client.serviceTimeoutAsyncRetry(waitingFuture);
    expect(TimeoutException.class, result);
    long resultTime = System.nanoTime();

    // Should get TimeoutException after 1500ms (3 attempts * 500ms), allow up to 3000ms
    assertThat("Time for result to complete", Duration.ofNanos(resultTime - startTime), lessThan(config.getTimeoutInDuration(3000)));
    
    // Expect all executions to be run
    assertEquals(client.getTimeoutAsyncRetryCounter(), 3, "Execution count after one call");
}
 
Example 13
Source Project: thorntail   Source File: FaultToleranceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testTimeout() throws InterruptedException, IllegalStateException, RestClientDefinitionException, MalformedURLException {
    HelloClient helloClient = RestClientBuilder.newBuilder().baseUrl(url).build(HelloClient.class);

    counter.reset(1);
    timer.reset(400);
    latch.reset(1);

    try {
        helloClient.helloTimeout();
        fail();
    } catch (TimeoutException expected) {
    }

    latch.await();
}
 
Example 14
Source Project: smallrye-fault-tolerance   Source File: TimeoutTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testTimeout() throws InterruptedException {
    TimingOutService.INTERRUPTED.set(false);
    boolean timeoutExceptionThrown = false;
    try {
        service.someSlowMethod(1500);
        fail("No timeout");
    } catch (TimeoutException expected) {
        timeoutExceptionThrown = true;
    } catch (Exception e) {
        fail("Unexpected: " + e.getMessage());
    }
    assertTrue(TimingOutService.INTERRUPTED.get());
    assertTrue(timeoutExceptionThrown);
}
 
Example 15
Source Project: smallrye-fault-tolerance   Source File: RetryTestBean.java    License: Apache License 2.0 5 votes vote down vote up
@Retry(retryOn = TimeoutException.class)
@Fallback(fallbackMethod = "fallback")
@Timeout(100L)
public String callWithRetryOnTimeoutException() {
    int attempt = this.attempt.getAndIncrement();
    if (attempt == 0) {
        sleep(5000L);
    }
    return "call" + attempt;
}
 
Example 16
Source Project: smallrye-fault-tolerance   Source File: RetryTestBean.java    License: Apache License 2.0 5 votes vote down vote up
@Retry(retryOn = TimeoutException.class, delay = 500)
@Bulkhead(2)
public String callWithNoRetryOnBulkhead() {
    int attempt = this.attempt.getAndIncrement();
    if (attempt < 2) {
        sleep(300L);
    }
    return "call" + attempt;
}
 
Example 17
Source Project: smallrye-fault-tolerance   Source File: RetryTestBean.java    License: Apache License 2.0 5 votes vote down vote up
@Retry(retryOn = TimeoutException.class, delay = 500)
@Bulkhead(2)
@Fallback(fallbackMethod = "fallback")
public String callWithFallbackAndNoRetryOnBulkhead() {
    int attempt = this.attempt.getAndIncrement();
    if (attempt < 2) {
        sleep(300L);
    }
    return "call" + attempt;
}
 
Example 18
Source Project: smallrye-fault-tolerance   Source File: TimeoutTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void delayed_value_timedOut() throws InterruptedException {
    Barrier invocationDelayBarrier = Barrier.interruptible();

    TestInvocation<String> invocation = TestInvocation.delayed(invocationDelayBarrier, () -> "foobar");
    TestThread<String> result = runOnTestThread(
            new Timeout<>(invocation, "test invocation", 1000, timeoutWatcher, null));
    watcherTimeoutElapsedBarrier.open();
    watcherExecutionInterruptedBarrier.await();
    assertThatThrownBy(result::await)
            .isExactlyInstanceOf(TimeoutException.class)
            .hasMessage("test invocation timed out");
    assertThat(timeoutWatcher.timeoutWatchWasCancelled()).isFalse();
}
 
Example 19
Source Project: smallrye-fault-tolerance   Source File: TimeoutTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void delayed_value_timedOutNoninterruptibly() throws InterruptedException {
    Barrier invocationDelayBarrier = Barrier.noninterruptible();

    TestInvocation<String> invocation = TestInvocation.delayed(invocationDelayBarrier, () -> "foobar");
    TestThread<String> result = runOnTestThread(
            new Timeout<>(invocation, "test invocation", 1000, timeoutWatcher, null));
    watcherTimeoutElapsedBarrier.open();
    watcherExecutionInterruptedBarrier.await();
    invocationDelayBarrier.open();
    assertThatThrownBy(result::await)
            .isExactlyInstanceOf(TimeoutException.class)
            .hasMessage("test invocation timed out");
    assertThat(timeoutWatcher.timeoutWatchWasCancelled()).isFalse();
}
 
Example 20
Source Project: smallrye-fault-tolerance   Source File: TimeoutTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void delayed_exception_timedOut() throws InterruptedException {
    Barrier invocationDelayBarrier = Barrier.interruptible();

    TestInvocation<Void> invocation = TestInvocation.delayed(invocationDelayBarrier, TestException::doThrow);
    TestThread<Void> result = runOnTestThread(new Timeout<>(invocation, "test invocation", 1000, timeoutWatcher, null));
    watcherTimeoutElapsedBarrier.open();
    watcherExecutionInterruptedBarrier.await();
    assertThatThrownBy(result::await)
            .isExactlyInstanceOf(TimeoutException.class)
            .hasMessage("test invocation timed out");
    assertThat(timeoutWatcher.timeoutWatchWasCancelled()).isFalse();
}
 
Example 21
Source Project: smallrye-fault-tolerance   Source File: TimeoutTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void delayed_exception_timedOutNoninterruptibly() throws InterruptedException {
    Barrier invocationDelayBarrier = Barrier.noninterruptible();

    TestInvocation<Void> invocation = TestInvocation.delayed(invocationDelayBarrier, TestException::doThrow);
    TestThread<Void> result = runOnTestThread(new Timeout<>(invocation, "test invocation", 1000, timeoutWatcher, null));
    watcherTimeoutElapsedBarrier.open();
    watcherExecutionInterruptedBarrier.await();
    invocationDelayBarrier.open();
    assertThatThrownBy(result::await)
            .isExactlyInstanceOf(TimeoutException.class)
            .hasMessage("test invocation timed out");
    assertThat(timeoutWatcher.timeoutWatchWasCancelled()).isFalse();
}
 
Example 22
@Test
public void shouldTimeOut() throws Exception {
    RunningStopwatch runningStopwatch = stopwatch.start();

    FaultToleranceStrategy<CompletionStage<String>> timeout = new CompletionStageTimeout<>(invocation(),
            "completion stage timeout", SLEEP_TIME, watcher, timeoutActionExecutor, null, true);

    assertThatThrownBy(timeout.apply(new InvocationContext<>(() -> {
        Thread.sleep(TIMEOUT);
        return completedStage("foobar");
    })).toCompletableFuture()::get)
            .isExactlyInstanceOf(ExecutionException.class)
            .hasCauseExactlyInstanceOf(TimeoutException.class);
    assertThat(runningStopwatch.elapsedTimeInMillis()).isCloseTo(SLEEP_TIME, tolerance);
}
 
Example 23
/**
 * Has a CircuitBreaker and Retries on TimeoutException
 * <p>
 * The method should never throw a TimeoutException so the retry should have no effect
 * 
 * @param throwException whether this method should throw a TestException to simulate an application failure
 * @return string "OK"
 */
@CircuitBreaker(requestVolumeThreshold = 4, failureRatio = 0.75, delay = 1000)
@Retry(retryOn = TimeoutException.class, maxRetries = 20, delay = 200)
@Asynchronous
// Delays scaled via config
public Future<String> serviceWithRetryOnTimeout(boolean throwException) {
    if (throwException) {
        throw new TestException("Test Exception");
    }
    else {
        return CompletableFuture.completedFuture("OK");
    }
}
 
Example 24
/**
 * Has a CircuitBreaker and Retries on TimeoutException
 * <p>
 * The method should never throw a TimeoutException so the retry should have no effect
 * 
 * @param throwException whether this method should throw a TestException to simulate an application failure
 * @return string "OK"
 */
@CircuitBreaker(requestVolumeThreshold = 4, failureRatio = 0.75, delay = 1000)
@Retry(retryOn = TimeoutException.class, maxRetries = 20, delay = 200)
// Scaled via config
public String serviceWithRetryOnTimeout(boolean throwException) {
    if (throwException) {
        throw new TestException();
    }
    else {
        return "OK";
    }
}
 
Example 25
/**
 * Test that a service is not retried if TimeoutException is not included in the retryOn attribute
 */
@Test
public void testRetryWithoutRetryOn() {
    try {
        clientForRetryTimeout.serviceWithoutRetryOn();
        fail("Timeout exception not thrown");
    }
    catch (TimeoutException e) {
        // expected
    }
    
    assertEquals(clientForRetryTimeout.getCounterForInvokingServiceWithoutRetryOn(), 1, "The execution count should be 1 (no retries)");
}
 
Example 26
/**
 * Test that a service is not retried if TimeoutException is included in the abortOn attribute
 */
@Test
public void testRetryWithAbortOn() {
    try {
        clientForRetryTimeout.serviceWithAbortOn();
        fail("Timeout exception not thrown");
    }
    catch (TimeoutException e) {
        // expected
    }
    
    assertEquals(clientForRetryTimeout.getCounterForInvokingServiceWithAbortOn(), 1, "The execution count should be 1 (no retries)");
}
 
Example 27
/**
 * Sleeps for 1000ms, times out after 500ms, retries once on anything but TimeoutException
 * 
 * @return {@code null}
 */
@Timeout(500)
@Retry(maxRetries = 1, abortOn = TimeoutException.class)
public String serviceWithAbortOn() {
    try {
        counterForInvokingServiceWithAbortOn++;
        Thread.sleep(config.getTimeoutInMillis(1000));
        fail("Timeout did not interrupt");
    }
    catch (InterruptedException e) {
        // expected
    }
    return null;
}
 
Example 28
/**
 * Test that the timeout timer is started when the execution is added to the queue
 * 
 * @throws InterruptedException if the test is interrupted
 * @throws ExecutionException 
 */
@Test
public void testTimeoutAsyncBulkheadQueueTimed() throws InterruptedException, ExecutionException {
    CompletableFuture<Void> waitingFutureA = newWaitingFuture();
    CompletableFuture<Void> waitingFutureB = newWaitingFuture();
    
    Future<Void> resultA = client.serviceTimeoutAsyncBulkheadQueueTimed(waitingFutureA);
    Thread.sleep(config.getTimeoutInMillis(100));
    
    long startTime = System.nanoTime();
    Future<Void> resultB = client.serviceTimeoutAsyncBulkheadQueueTimed(waitingFutureB);
    
    Thread.sleep(config.getTimeoutInMillis(300));
    
    // Allow call A to finish, this should allow call B to start
    waitingFutureA.complete(null);
    
    // Assert there were no exceptions for call A
    resultA.get();
    
    // Wait for call B to time out
    expect(TimeoutException.class, resultB);
    long endTime = System.nanoTime();
    
    // B should time out 500ms after it was submitted, even though it spent 300ms queued
    // Allow up to 750ms. Bound is tighter here as more than 800ms would represent incorrect behavior
    assertThat("Time taken for call B to timeout", Duration.ofNanos(endTime - startTime), lessThan(config.getTimeoutInDuration(750)));
}
 
Example 29
private void doTest(ExceptionThrowingAction action) {
    long start = System.nanoTime();
    expect(TimeoutException.class, action);
    long end = System.nanoTime();

    long durationInMillis = Duration.ofNanos(end - start).toMillis();
    assertThat(durationInMillis, greaterThan(TCKConfig.getConfig().getTimeoutInMillis(800)));
    assertThat(durationInMillis, lessThan(TCKConfig.getConfig().getTimeoutInMillis(2000)));
}
 
Example 30
Source Project: smallrye-fault-tolerance   Source File: Timeout.java    License: Apache License 2.0 4 votes vote down vote up
static TimeoutException timeoutException(String description) {
    return new TimeoutException(description + " timed out");
}