Search in sources :

Example 6 with CancellationException

use of java.util.concurrent.CancellationException in project guava by google.

the class TestingExecutorsTest method testNoOpScheduledExecutorInvokeAll.

public void testNoOpScheduledExecutorInvokeAll() throws ExecutionException, InterruptedException {
    ListeningScheduledExecutorService executor = TestingExecutors.noOpScheduledExecutor();
    taskDone = false;
    Callable<Boolean> task = new Callable<Boolean>() {

        @Override
        public Boolean call() {
            taskDone = true;
            return taskDone;
        }
    };
    List<Future<Boolean>> futureList = executor.invokeAll(ImmutableList.of(task), 10, TimeUnit.MILLISECONDS);
    Future<Boolean> future = futureList.get(0);
    assertFalse(taskDone);
    assertTrue(future.isDone());
    try {
        future.get();
        fail();
    } catch (CancellationException e) {
    // pass
    }
}
Also used : ListeningScheduledExecutorService(com.google.common.util.concurrent.ListeningScheduledExecutorService) CancellationException(java.util.concurrent.CancellationException) Future(java.util.concurrent.Future) ScheduledFuture(java.util.concurrent.ScheduledFuture) Callable(java.util.concurrent.Callable)

Example 7 with CancellationException

use of java.util.concurrent.CancellationException in project guava by google.

the class AbstractFutureTest method testSetFutureCancelBash.

// setFuture and cancel() interact in more complicated ways than the other setters.
public void testSetFutureCancelBash() {
    final int size = 50;
    final CyclicBarrier barrier = new CyclicBarrier(// for the setter threads
    2 + // for the listeners
    size + // for the get threads,
    size + // for the main thread
    1);
    final ExecutorService executor = Executors.newFixedThreadPool(barrier.getParties());
    final AtomicReference<AbstractFuture<String>> currentFuture = Atomics.newReference();
    final AtomicReference<AbstractFuture<String>> setFutureFuture = Atomics.newReference();
    final AtomicBoolean setFutureSetSucess = new AtomicBoolean();
    final AtomicBoolean setFutureCompletionSucess = new AtomicBoolean();
    final AtomicBoolean cancellationSucess = new AtomicBoolean();
    Runnable cancelRunnable = new Runnable() {

        @Override
        public void run() {
            cancellationSucess.set(currentFuture.get().cancel(true));
            awaitUnchecked(barrier);
        }
    };
    Runnable setFutureCompleteSucessFullyRunnable = new Runnable() {

        @Override
        public void run() {
            AbstractFuture<String> future = setFutureFuture.get();
            setFutureSetSucess.set(currentFuture.get().setFuture(future));
            setFutureCompletionSucess.set(future.set("hello-async-world"));
            awaitUnchecked(barrier);
        }
    };
    final Set<Object> finalResults = Collections.synchronizedSet(Sets.newIdentityHashSet());
    Runnable collectResultsRunnable = new Runnable() {

        @Override
        public void run() {
            try {
                String result = Uninterruptibles.getUninterruptibly(currentFuture.get());
                finalResults.add(result);
            } catch (ExecutionException e) {
                finalResults.add(e.getCause());
            } catch (CancellationException e) {
                finalResults.add(CancellationException.class);
            } finally {
                awaitUnchecked(barrier);
            }
        }
    };
    Runnable collectResultsTimedGetRunnable = new Runnable() {

        @Override
        public void run() {
            Future<String> future = currentFuture.get();
            while (true) {
                try {
                    String result = Uninterruptibles.getUninterruptibly(future, 0, TimeUnit.SECONDS);
                    finalResults.add(result);
                    break;
                } catch (ExecutionException e) {
                    finalResults.add(e.getCause());
                    break;
                } catch (CancellationException e) {
                    finalResults.add(CancellationException.class);
                    break;
                } catch (TimeoutException e) {
                // loop
                }
            }
            awaitUnchecked(barrier);
        }
    };
    List<Runnable> allTasks = new ArrayList<Runnable>();
    allTasks.add(cancelRunnable);
    allTasks.add(setFutureCompleteSucessFullyRunnable);
    for (int k = 0; k < size; k++) {
        // For each listener we add a task that submits it to the executor directly for the blocking
        // get usecase and another task that adds it as a listener to the future to exercise both
        // racing addListener calls and addListener calls completing after the future completes.
        final Runnable listener = k % 2 == 0 ? collectResultsRunnable : collectResultsTimedGetRunnable;
        allTasks.add(listener);
        allTasks.add(new Runnable() {

            @Override
            public void run() {
                currentFuture.get().addListener(listener, executor);
            }
        });
    }
    // sanity check
    assertEquals(allTasks.size() + 1, barrier.getParties());
    for (int i = 0; i < 1000; i++) {
        Collections.shuffle(allTasks);
        final AbstractFuture<String> future = new AbstractFuture<String>() {
        };
        final AbstractFuture<String> setFuture = new AbstractFuture<String>() {
        };
        currentFuture.set(future);
        setFutureFuture.set(setFuture);
        for (Runnable task : allTasks) {
            executor.execute(task);
        }
        awaitUnchecked(barrier);
        assertThat(future.isDone()).isTrue();
        // inspect state and ensure it is correct!
        // asserts that all get calling threads received the same value
        Object result = Iterables.getOnlyElement(finalResults);
        if (result == CancellationException.class) {
            assertTrue(future.isCancelled());
            assertTrue(cancellationSucess.get());
            // 3. after setFuture and set() are called but before the listener completes.
            if (!setFutureSetSucess.get() || !setFutureCompletionSucess.get()) {
                // If setFuture fails or set on the future fails then it must be because that future was
                // cancelled
                assertTrue(setFuture.isCancelled());
                // we only call cancel(true)
                assertTrue(setFuture.wasInterrupted());
            }
        } else {
            // set on the future completed
            assertFalse(cancellationSucess.get());
            assertTrue(setFutureSetSucess.get());
            assertTrue(setFutureCompletionSucess.get());
        }
        // reset for next iteration
        setFutureSetSucess.set(false);
        setFutureCompletionSucess.set(false);
        cancellationSucess.set(false);
        finalResults.clear();
    }
    executor.shutdown();
}
Also used : ArrayList(java.util.ArrayList) CyclicBarrier(java.util.concurrent.CyclicBarrier) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CancellationException(java.util.concurrent.CancellationException) ExecutorService(java.util.concurrent.ExecutorService) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException)

Example 8 with CancellationException

use of java.util.concurrent.CancellationException in project guava by google.

the class FuturesTest method testWhenAllComplete_interrupted.

// threads
@GwtIncompatible
public void testWhenAllComplete_interrupted() throws Exception {
    SettableFuture<String> stringFuture = SettableFuture.create();
    SettableFuture<Boolean> booleanFuture = SettableFuture.create();
    final CountDownLatch inFunction = new CountDownLatch(1);
    final CountDownLatch gotException = new CountDownLatch(1);
    AsyncCallable<String> combiner = new AsyncCallable<String>() {

        @Override
        public ListenableFuture<String> call() throws Exception {
            inFunction.countDown();
            try {
                // wait for interrupt
                new CountDownLatch(1).await();
            } catch (InterruptedException expected) {
                gotException.countDown();
                throw expected;
            }
            return immediateFuture("a");
        }
    };
    ListenableFuture<String> futureResult = whenAllComplete(stringFuture, booleanFuture).callAsync(combiner, newSingleThreadExecutor());
    stringFuture.set("value");
    booleanFuture.set(true);
    inFunction.await();
    futureResult.cancel(true);
    try {
        futureResult.get();
        fail();
    } catch (CancellationException expected) {
    }
    gotException.await();
}
Also used : CancellationException(java.util.concurrent.CancellationException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CountDownLatch(java.util.concurrent.CountDownLatch) GwtIncompatible(com.google.common.annotations.GwtIncompatible)

Example 9 with CancellationException

use of java.util.concurrent.CancellationException in project guava by google.

the class FuturesTest method testWhenAllComplete_cancelledNotInterrupted.

// threads
@GwtIncompatible
public void testWhenAllComplete_cancelledNotInterrupted() throws Exception {
    SettableFuture<String> stringFuture = SettableFuture.create();
    SettableFuture<Boolean> booleanFuture = SettableFuture.create();
    final CountDownLatch inFunction = new CountDownLatch(1);
    final CountDownLatch shouldCompleteFunction = new CountDownLatch(1);
    final SettableFuture<String> resultFuture = SettableFuture.create();
    AsyncCallable<String> combiner = new AsyncCallable<String>() {

        @Override
        public ListenableFuture<String> call() throws Exception {
            inFunction.countDown();
            shouldCompleteFunction.await();
            return resultFuture;
        }
    };
    ListenableFuture<String> futureResult = whenAllComplete(stringFuture, booleanFuture).callAsync(combiner, newSingleThreadExecutor());
    stringFuture.set("value");
    booleanFuture.set(true);
    inFunction.await();
    futureResult.cancel(false);
    shouldCompleteFunction.countDown();
    try {
        futureResult.get();
        fail();
    } catch (CancellationException expected) {
    }
    try {
        resultFuture.get();
        fail();
    } catch (CancellationException expected) {
    }
}
Also used : CancellationException(java.util.concurrent.CancellationException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CountDownLatch(java.util.concurrent.CountDownLatch) GwtIncompatible(com.google.common.annotations.GwtIncompatible)

Example 10 with CancellationException

use of java.util.concurrent.CancellationException in project guava by google.

the class FuturesTest method testCatchingAsync_interruptPropagatesToTransformingThread.

// threads
@GwtIncompatible
public void testCatchingAsync_interruptPropagatesToTransformingThread() throws Exception {
    SettableFuture<String> input = SettableFuture.create();
    final CountDownLatch inFunction = new CountDownLatch(1);
    final CountDownLatch shouldCompleteFunction = new CountDownLatch(1);
    final CountDownLatch gotException = new CountDownLatch(1);
    AsyncFunction<Throwable, String> function = new AsyncFunction<Throwable, String>() {

        @Override
        public ListenableFuture<String> apply(Throwable t) throws Exception {
            inFunction.countDown();
            try {
                shouldCompleteFunction.await();
            } catch (InterruptedException expected) {
                gotException.countDown();
                throw expected;
            }
            return immediateFuture("a");
        }
    };
    ListenableFuture<String> futureResult = catchingAsync(input, Exception.class, function, newSingleThreadExecutor());
    input.setException(new Exception());
    inFunction.await();
    futureResult.cancel(true);
    shouldCompleteFunction.countDown();
    try {
        futureResult.get();
        fail();
    } catch (CancellationException expected) {
    }
    // TODO(cpovirk): implement interruption, updating this test:
    // https://github.com/google/guava/issues/1989
    assertEquals(1, gotException.getCount());
// gotException.await();
}
Also used : CancellationException(java.util.concurrent.CancellationException) CountDownLatch(java.util.concurrent.CountDownLatch) TimeoutException(java.util.concurrent.TimeoutException) CancellationException(java.util.concurrent.CancellationException) FileNotFoundException(java.io.FileNotFoundException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) GwtIncompatible(com.google.common.annotations.GwtIncompatible)

Aggregations

CancellationException (java.util.concurrent.CancellationException)196 ExecutionException (java.util.concurrent.ExecutionException)88 TimeoutException (java.util.concurrent.TimeoutException)50 Test (org.junit.Test)34 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)25 IOException (java.io.IOException)24 CountDownLatch (java.util.concurrent.CountDownLatch)23 Future (java.util.concurrent.Future)23 ArrayList (java.util.ArrayList)18 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)17 Callable (java.util.concurrent.Callable)16 ExecutorService (java.util.concurrent.ExecutorService)13 File (java.io.File)11 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)8 InvocationTargetException (java.lang.reflect.InvocationTargetException)7 List (java.util.List)7 CompletableFuture (java.util.concurrent.CompletableFuture)7 FutureTask (java.util.concurrent.FutureTask)7 Handler (android.os.Handler)6 GwtIncompatible (com.google.common.annotations.GwtIncompatible)6