Example usage for java.util.concurrent ExecutorService invokeAny

List of usage examples for java.util.concurrent ExecutorService invokeAny

Introduction

In this page you can find the example usage for java.util.concurrent ExecutorService invokeAny.

Prototype

<T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException;

Source Link

Document

Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception), if any do.

Usage

From source file:com.microsoft.azure.servicebus.samples.deadletterqueue.DeadletterQueue.java

private void waitForEnter(int seconds) {
    ExecutorService executor = Executors.newCachedThreadPool();
    try {//from   w w w .  ja  v  a 2s  .  c  o m
        executor.invokeAny(Arrays.asList(() -> {
            System.in.read();
            return 0;
        }, () -> {
            Thread.sleep(seconds * 1000);
            return 0;
        }));
    } catch (Exception e) {
        // absorb
    }
}

From source file:com.brienwheeler.lib.concurrent.ExecutorsTest.java

@Test
public void testNewSingleThreadExecutorInvokeAny()
        throws InterruptedException, ExecutionException, TimeoutException {
    NamedThreadFactory threadFactory = new NamedThreadFactory(THREAD_FACTORY_NAME);
    ExecutorService executor = Executors.newSingleThreadExecutor(threadFactory);

    IntCallable one = new IntCallable(1);
    IntCallable two = new IntCallable(2);
    ArrayList<Callable<Integer>> tasks = new ArrayList<Callable<Integer>>();
    tasks.add(one);/*from w w w.  jav  a2  s. c o m*/
    tasks.add(two);

    Integer result = executor.invokeAny(tasks);
    Assert.assertTrue(result == 1 || result == 2);

    result = executor.invokeAny(tasks, 10, TimeUnit.MILLISECONDS);
    Assert.assertTrue(result == 1 || result == 2);

    executor.shutdown();
}