java.util.concurrent.CompletableFuture

Here are the examples of the java api class java.util.concurrent.CompletableFuture taken from open source projects.

1. CompletableFutureTest#testToString()

Project: openjdk
File: CompletableFutureTest.java
/**
     * toString indicates current completion state
     */
public void testToString() {
    CompletableFuture<String> f;
    f = new CompletableFuture<String>();
    assertTrue(f.toString().contains("[Not completed]"));
    assertTrue(f.complete("foo"));
    assertTrue(f.toString().contains("[Completed normally]"));
    f = new CompletableFuture<String>();
    assertTrue(f.completeExceptionally(new IndexOutOfBoundsException()));
    assertTrue(f.toString().contains("[Completed exceptionally]"));
    for (boolean mayInterruptIfRunning : new boolean[] { true, false }) {
        f = new CompletableFuture<String>();
        assertTrue(f.cancel(mayInterruptIfRunning));
        assertTrue(f.toString().contains("[Completed exceptionally]"));
    }
}

2. CompletableFutureTest#testObtrudeValue()

Project: openjdk
File: CompletableFutureTest.java
/**
     * obtrudeValue forces completion with given value
     */
public void testObtrudeValue() {
    CompletableFuture<Integer> f = new CompletableFuture<>();
    checkIncomplete(f);
    assertTrue(f.complete(one));
    checkCompletedNormally(f, one);
    f.obtrudeValue(three);
    checkCompletedNormally(f, three);
    f.obtrudeValue(two);
    checkCompletedNormally(f, two);
    f = new CompletableFuture<>();
    f.obtrudeValue(three);
    checkCompletedNormally(f, three);
    f.obtrudeValue(null);
    checkCompletedNormally(f, null);
    f = new CompletableFuture<>();
    f.completeExceptionally(new CFException());
    f.obtrudeValue(four);
    checkCompletedNormally(f, four);
}

3. ParallelTest#runThread()

Project: cyclops-react
File: ParallelTest.java
@Test
public void runThread() {
    CompletableFuture cf = new CompletableFuture();
    LazyFutureStream s = LazyReact.sequentialBuilder().withMaxActive(MaxActive.IO).async().generateAsync(() -> 1).limit(1_000_000);
    for (int x = 0; x < 60; x++) {
        s = s.then(Function.identity());
    }
    //s.runOnCurrent();
    s.runThread(() -> cf.complete(true));
    cf.join();
}

4. RxJavaConversionTest#query()

Project: cyclops-react
File: RxJavaConversionTest.java
private CompletableFuture<List<String>> query(String string) {
    CompletableFuture future = new CompletableFuture();
    future.complete(Arrays.asList("http://blog.danlew.net/2014/09/22/grokking-rxjava-part-2", "http://blog.danlew.net/2014/09/30/grokking-rxjava-part-3", "http://blog.danlew.net/2014/09/30/grokking-rxjava-part-3", "http://blog.danlew.net/2014/09/30/grokking-rxjava-part-3", "http://blog.danlew.net/2014/09/30/grokking-rxjava-part-3", "http://blog.danlew.net/2014/09/30/grokking-rxjava-part-3", "http://blog.danlew.net/2014/09/30/grokking-rxjava-part-3", "http://blog.danlew.net/2014/09/30/grokking-rxjava-part-3", "http://blog.danlew.net/2014/09/30/grokking-rxjava-part-3"));
    return future;
}

5. MiddlewaresTest#setUp()

Project: apollo
File: MiddlewaresTest.java
@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    future = new CompletableFuture<>();
    serializationFuture = new CompletableFuture<>();
    when(requestContext.request()).thenReturn(request);
    when(request.method()).thenReturn("GET");
    delegate =  requestContext -> future;
    serializationDelegate =  requestContext -> serializationFuture;
}

6. Tutorial#redisBenchmark()

Project: Orestes-Bloomfilter
File: Tutorial.java
public static void redisBenchmark() {
    int connections = 100;
    RedisPool pool = new RedisPool("localhost", 6379, connections);
    ExecutorService exec = Executors.newFixedThreadPool(connections);
    int rounds = 200_000;
    int perThread = rounds / connections;
    CompletableFuture[] futures = new CompletableFuture[connections];
    Long start = System.currentTimeMillis();
    for (int i = 0; i < connections; i++) {
        futures[i] = CompletableFuture.runAsync(() -> {
            pool.safelyDo( jedis -> {
                for (int j = 0; j < perThread; j++) {
                    jedis.set("key" + Math.random(), RandomStringUtils.random(50));
                }
            });
        }, exec);
    }
    CompletableFuture.allOf(futures).join();
    Long stop = System.currentTimeMillis();
    System.out.printf("Time to complete %s sets: %s ms\n", rounds, stop - start);
}

7. ClusterState#join()

Project: copycat
File: ClusterState.java
/**
   * Starts the join to the cluster.
   */
private synchronized CompletableFuture<Void> join() {
    joinFuture = new CompletableFuture<>();
    context.getThreadContext().executor().execute(() -> {
        // Transition the server to the appropriate state for the local member type.
        context.transition(member.type());
        // Attempt to join the cluster. If the local member is ACTIVE then failing to join the cluster
        // will result in the member attempting to get elected. This allows initial clusters to form.
        List<MemberState> activeMembers = getActiveMemberStates();
        if (!activeMembers.isEmpty()) {
            join(getActiveMemberStates().iterator());
        } else {
            joinFuture.complete(null);
        }
    });
    return joinFuture.whenComplete(( result,  error) -> joinFuture = null);
}

8. AbstractMessageProducer#sendSync()

Project: atomix
File: AbstractMessageProducer.java
/**
   * Sends an atomic message.
   */
private CompletableFuture sendSync(String member, T message) {
    CompletableFuture future = new BlockingFuture();
    final long messageId = ++this.messageId;
    messageFutures.put(messageId, future);
    client.producerService().send(new GroupCommands.Message(member, id, name, messageId, message, delivery, execution)).whenComplete(( result,  error) -> {
        if (error != null) {
            CompletableFuture messageFuture = messageFutures.remove(messageId);
            if (messageFuture != null) {
                messageFuture.completeExceptionally(error);
            }
        }
    });
    return future;
}

9. AbstractMessageProducer#onAck()

Project: atomix
File: AbstractMessageProducer.java
/**
   * Called when a message acknowledgement is received.
   *
   * @param ack The message acknowledgement.
   */
@SuppressWarnings("unchecked")
void onAck(GroupCommands.Ack ack) {
    CompletableFuture messageFuture = messageFutures.remove(messageId);
    if (messageFuture != null) {
        if (execution == Execution.SYNC) {
            if (ack.succeeded()) {
                messageFuture.complete(null);
            } else {
                messageFuture.completeExceptionally(new MessageFailedException("message failed"));
            }
        } else if (execution == Execution.REQUEST_REPLY) {
            if (ack.succeeded()) {
                messageFuture.complete(ack.message());
            } else {
                messageFuture.completeExceptionally(new MessageFailedException("message failed"));
            }
        }
    }
}

10. ReplicationServiceTest#testCanBootstrapThreeNodeCluster()

Project: gatekeeper
File: ReplicationServiceTest.java
@Test
public void testCanBootstrapThreeNodeCluster() throws IOException, InterruptedException {
    Path dataDirectoryA = createTemporaryDirectory();
    Path dataDirectoryB = createTemporaryDirectory();
    Path dataDirectoryC = createTemporaryDirectory();
    Configuration configurationA = new Configuration();
    Configuration configurationB = new Configuration();
    Configuration configurationC = new Configuration();
    configurationA.replication.bindAddress = configurationB.replication.bindAddress = configurationC.replication.bindAddress = "127.0.0.1";
    configurationA.replication.bootstrap = Boolean.TRUE;
    configurationB.replication.bootstrap = configurationC.replication.bootstrap = Boolean.FALSE;
    configurationA.replication.server = configurationB.replication.server = configurationC.replication.server = Boolean.TRUE;
    configurationA.replication.dataDirectory = dataDirectoryA.toString();
    configurationB.replication.dataDirectory = dataDirectoryB.toString();
    configurationC.replication.dataDirectory = dataDirectoryC.toString();
    configurationA.replication.bindPort = 63513;
    configurationB.replication.bindPort = 63514;
    configurationC.replication.bindPort = 63515;
    List<String> nodes = Arrays.asList("127.0.0.1:63513", "127.0.0.1:63514", "127.0.0.1:63515");
    configurationA.replication.nodes.addAll(nodes);
    configurationB.replication.nodes.addAll(nodes);
    configurationC.replication.nodes.addAll(nodes);
    ReplicationService replicationA = new ReplicationService(configurationA);
    ReplicationService replicationB = new ReplicationService(configurationB);
    ReplicationService replicationC = new ReplicationService(configurationC);
    CompletableFuture completableA = replicationA.start();
    CompletableFuture completableB = replicationB.start();
    CompletableFuture completableC = replicationC.start();
    completableA.join();
    completableB.join();
    completableC.join();
    replicationA.close();
    replicationB.close();
    replicationC.close();
}

11. TaskImplementationTest#testAnyOfVariations()

Project: orbit
File: TaskImplementationTest.java
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testAnyOfVariations() {
    CTask<Integer> t1 = new CTask<>();
    CTask t2 = new CTask<>();
    CTask<?> t3 = new CTask<>();
    CompletableFuture c4 = new CompletableFuture();
    Task group_regular = CTask.anyOf(t1, t2, t3);
    Task group_array = CTask.anyOf(new CompletableFuture[] { t1, t2, t3 });
    Task group_array2 = CTask.anyOf(new CTask[] { t1, t2, t3 });
    Task group_collection = CTask.anyOf(Arrays.asList(t1, t2, t3));
    Task group_stream = CTask.anyOf(Arrays.asList(t1, t2, t3).stream());
    Stream<CTask> stream = Arrays.asList(t1, t2, t3).stream();
    Task group_stream2 = CTask.anyOf(stream);
    Task group_stream3 = CTask.anyOf(Arrays.asList(c4).stream());
    Stream<CompletableFuture> stream4 = Arrays.asList(t1, t2, t3, c4).stream();
    Task group_stream4 = CTask.anyOf(stream4);
    Task group_stream5 = CTask.anyOf(Arrays.asList(t1, t2, t3, c4).stream());
    t1.complete(1);
    c4.complete(4);
    assertTrue(group_regular.isDone());
    assertTrue(group_array.isDone());
    assertTrue(group_array2.isDone());
    assertTrue(group_stream.isDone());
    assertTrue(group_stream2.isDone());
    assertTrue(group_stream3.isDone());
    assertTrue(group_stream4.isDone());
    assertTrue(group_stream5.isDone());
    assertTrue(group_collection.isDone());
}

12. TaskImplementationTest#testAllOfVariations()

Project: orbit
File: TaskImplementationTest.java
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testAllOfVariations() {
    CTask<Integer> t1 = new CTask();
    CTask t2 = new CTask();
    CTask t3 = new CTask();
    CompletableFuture c4 = new CompletableFuture();
    Task all_regular = CTask.allOf(t1, t2, t3);
    Task all_array = CTask.allOf(new CompletableFuture[] { t1, t2, t3 });
    Task all_array2 = CTask.allOf(new CTask[] { t1, t2, t3 });
    Task all_collection = CTask.allOf(Arrays.asList(t1, t2, t3));
    Task all_stream = CTask.allOf(Arrays.asList(t1, t2, t3).stream());
    Stream<CTask> stream = Arrays.asList(t1, t2, t3).stream();
    Task all_stream2 = CTask.allOf(stream);
    Task all_stream3 = CTask.allOf(Arrays.asList(c4).stream());
    Stream<CompletableFuture> stream4 = Arrays.asList(t1, t2, t3, c4).stream();
    Task all_stream4 = Task.allOf(stream4);
    Task all_stream5 = Task.allOf(Arrays.asList(t1, t2, t3, c4).stream());
    t1.complete(1);
    t2.completeExceptionally(new RuntimeException());
    t3.complete(3);
    c4.complete(4);
    assertTrue(all_regular.isDone());
    assertTrue(all_array.isDone());
    assertTrue(all_array2.isDone());
    assertTrue(all_stream.isDone());
    assertTrue(all_stream2.isDone());
    assertTrue(all_stream3.isDone());
    assertTrue(all_stream4.isDone());
    assertTrue(all_stream5.isDone());
    assertTrue(all_collection.isDone());
}

13. CompletableFuturesTest#setup()

Project: cyclops-react
File: CompletableFuturesTest.java
@Before
public void setup() {
    just = CompletableFuture.completedFuture(10);
    none = new CompletableFuture<>();
    none.completeExceptionally(new Exception("boo"));
    active = new CompletableFuture<>();
    just2 = CompletableFuture.completedFuture(20);
}

14. CompletableFutureAnyMValueTest#setUp()

Project: cyclops-react
File: CompletableFutureAnyMValueTest.java
@Before
public void setUp() throws Exception {
    just = AnyM.fromCompletableFuture(CompletableFuture.completedFuture(10));
    CompletableFuture error = new CompletableFuture();
    error.completeExceptionally(new RuntimeException());
    none = AnyM.fromCompletableFuture(error);
}

15. TestMoreFutures#testUnmodifiableFutureCancelPropagation()

Project: airlift
File: TestMoreFutures.java
@Test
public void testUnmodifiableFutureCancelPropagation() throws Exception {
    CompletableFuture<String> future = new CompletableFuture<>();
    CompletableFuture<String> unmodifiableFuture = unmodifiableFuture(future, true);
    assertTrue(unmodifiableFuture.cancel(false));
    assertTrue(future.isDone());
    assertTrue(future.isCancelled());
    assertTrue(unmodifiableFuture.isDone());
    assertTrue(unmodifiableFuture.isCancelled());
    future = new CompletableFuture<>();
    unmodifiableFuture = unmodifiableFuture(future, true);
    assertTrue(unmodifiableFuture.cancel(true));
    assertTrue(future.isDone());
    assertTrue(future.isCancelled());
    assertTrue(unmodifiableFuture.isDone());
    assertTrue(unmodifiableFuture.isCancelled());
    future = new CompletableFuture<>();
    unmodifiableFuture = unmodifiableFuture(future, true);
    assertTrue(unmodifiableFuture.completeExceptionally(new CancellationException()));
    assertTrue(future.isDone());
    assertTrue(future.isCancelled());
    assertTrue(unmodifiableFuture.isDone());
    assertTrue(unmodifiableFuture.isCancelled());
}

16. GremlinServer#stop()

Project: tinkerpop
File: GremlinServer.java
/**
     * Stop Gremlin Server and free the port binding. Note that multiple calls to this method will return the
     * same instance of the {@link java.util.concurrent.CompletableFuture}.
     */
public synchronized CompletableFuture<Void> stop() {
    if (serverStopped != null) {
        // shutdown has started so don't fire it off again
        return serverStopped;
    }
    serverStopped = new CompletableFuture<>();
    final CountDownLatch servicesLeftToShutdown = new CountDownLatch(3);
    // release resources in the OpProcessors (e.g. kill sessions)
    OpLoader.getProcessors().entrySet().forEach( kv -> {
        logger.info("Shutting down OpProcessor[{}]", kv.getKey());
        try {
            kv.getValue().close();
        } catch (Exception ex) {
            logger.warn("Shutdown will continue but, there was an error encountered while closing " + kv.getKey(), ex);
        }
    });
    // of port conflict.  in that case, there's no need to wait for the channel to close.
    if (null == ch)
        servicesLeftToShutdown.countDown();
    else
        ch.close().addListener( f -> servicesLeftToShutdown.countDown());
    logger.info("Shutting down thread pools.");
    try {
        gremlinExecutorService.shutdown();
    } finally {
        logger.debug("Shutdown Gremlin thread pool.");
    }
    try {
        workerGroup.shutdownGracefully().addListener((GenericFutureListener)  f -> servicesLeftToShutdown.countDown());
    } finally {
        logger.debug("Shutdown Worker thread pool.");
    }
    try {
        bossGroup.shutdownGracefully().addListener((GenericFutureListener)  f -> servicesLeftToShutdown.countDown());
    } finally {
        logger.debug("Shutdown Boss thread pool.");
    }
    // channel is shutdown as are the thread pools - time to kill graphs as nothing else should be acting on them
    new Thread(() -> {
        serverGremlinExecutor.getHooks().forEach( hook -> {
            logger.info("Executing shutdown {}", LifeCycleHook.class.getSimpleName());
            try {
                hook.onShutDown(new LifeCycleHook.Context(logger));
            } catch (UnsupportedOperationExceptionUndeclaredThrowableException |  uoe) {
            }
        });
        try {
            gremlinExecutorService.awaitTermination(30000, TimeUnit.MILLISECONDS);
        } catch (InterruptedException ie) {
            logger.warn("Timeout waiting for Gremlin thread pool to shutdown - continuing with shutdown process.");
        }
        try {
            servicesLeftToShutdown.await(30000, TimeUnit.MILLISECONDS);
        } catch (InterruptedException ie) {
            logger.warn("Timeout waiting for boss/worker thread pools to shutdown - continuing with shutdown process.");
        }
        serverGremlinExecutor.getGraphManager().getGraphs().forEach(( k,  v) -> {
            logger.debug("Closing Graph instance [{}]", k);
            try {
                v.close();
            } catch (Exception ex) {
                logger.warn(String.format("Exception while closing Graph instance [%s]", k), ex);
            } finally {
                logger.info("Closed Graph instance [{}]", k);
            }
        });
        logger.info("Gremlin Server - shutdown complete");
        serverStopped.complete(null);
    }, SERVER_THREAD_PREFIX + "stop").start();
    return serverStopped;
}

17. GremlinServer#start()

Project: tinkerpop
File: GremlinServer.java
/**
     * Start Gremlin Server with {@link Settings} provided to the constructor.
     */
public synchronized CompletableFuture<ServerGremlinExecutor<EventLoopGroup>> start() throws Exception {
    if (serverStarted != null) {
        // server already started - don't get it rolling again
        return serverStarted;
    }
    serverStarted = new CompletableFuture<>();
    final CompletableFuture<ServerGremlinExecutor<EventLoopGroup>> serverReadyFuture = serverStarted;
    try {
        final ServerBootstrap b = new ServerBootstrap();
        // when high value is reached then the channel becomes non-writable and stays like that until the
        // low value is so that there is time to recover
        b.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, settings.writeBufferLowWaterMark);
        b.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, settings.writeBufferHighWaterMark);
        b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
        // fire off any lifecycle scripts that were provided by the user. hooks get initialized during
        // ServerGremlinExecutor initialization
        serverGremlinExecutor.getHooks().forEach( hook -> {
            logger.info("Executing start up {}", LifeCycleHook.class.getSimpleName());
            try {
                hook.onStartUp(new LifeCycleHook.Context(logger));
            } catch (UnsupportedOperationException uoe) {
            }
        });
        final Channelizer channelizer = createChannelizer(settings);
        channelizer.init(serverGremlinExecutor);
        b.group(bossGroup, workerGroup).childHandler(channelizer);
        if (isEpollEnabled) {
            b.channel(EpollServerSocketChannel.class);
        } else {
            b.channel(NioServerSocketChannel.class);
        }
        // bind to host/port and wait for channel to be ready
        b.bind(settings.host, settings.port).addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(final ChannelFuture channelFuture) throws Exception {
                if (channelFuture.isSuccess()) {
                    ch = channelFuture.channel();
                    logger.info("Gremlin Server configured with worker thread pool of {}, gremlin pool of {} and boss thread pool of {}.", settings.threadPoolWorker, settings.gremlinPool, settings.threadPoolBoss);
                    logger.info("Channel started at port {}.", settings.port);
                    serverReadyFuture.complete(serverGremlinExecutor);
                } else {
                    serverReadyFuture.completeExceptionally(new IOException(String.format("Could not bind to %s and %s - perhaps something else is bound to that address.", settings.host, settings.port)));
                }
            }
        });
    } catch (Exception ex) {
        logger.error("Gremlin Server Error", ex);
        serverReadyFuture.completeExceptionally(ex);
    }
    return serverStarted;
}

18. AbstractResultQueueTest#setup()

Project: tinkerpop
File: AbstractResultQueueTest.java
@Before
public void setup() {
    final LinkedBlockingQueue<Result> resultLinkedBlockingQueue = new LinkedBlockingQueue<>();
    readCompleted = new CompletableFuture<>();
    resultQueue = new ResultQueue(resultLinkedBlockingQueue, readCompleted);
}

19. BloomFilterTest#testMultiThreadedAddAndRemove()

Project: Orestes-Bloomfilter
File: BloomFilterTest.java
@Test
public void testMultiThreadedAddAndRemove() {
    ExecutorService exec = Executors.newFixedThreadPool(10);
    BloomFilter<String> filter = createFilter(name, 100_000, 0.001, HashMethod.Murmur2);
    int rounds = 100;
    List<String> inserted = IntStream.range(0, rounds).mapToObj( i -> "obj" + String.valueOf(i)).collect(Collectors.toList());
    CompletableFuture[] futures = new CompletableFuture[rounds];
    for (int i = 0; i < rounds; i++) {
        String obj = inserted.get(i);
        futures[i] = CompletableFuture.runAsync(() -> {
            filter.add(obj);
            assertTrue(filter.contains(obj));
            if (counting) {
                ((CountingBloomFilter<String>) filter).remove(obj);
                boolean contained = filter.contains(obj);
                assertFalse(contained);
                filter.add(obj);
                assertTrue(filter.contains(obj));
            }
        }, exec);
    }
    CompletableFuture.allOf(futures).join();
    List<String> notInserted = IntStream.range(rounds, rounds + 50).mapToObj(String::valueOf).collect(Collectors.toList());
    inserted.forEach( obj -> {
        assertTrue(filter.contains(obj));
    });
    notInserted.forEach( obj -> {
        boolean found = filter.contains(obj);
        assertFalse(found);
    });
    assertTrue(filter.containsAll(inserted));
    filter.remove();
}

20. Task#allOf()

Project: orbit
File: Task.java
/**
     * @throws NullPointerException if the stream or any of its elements are
     *                              {@code null}
     */
public static <F extends CompletableFuture<?>> Task<Void> allOf(Stream<F> cfs) {
    final List<F> futureList = cfs.collect(Collectors.toList());
    @SuppressWarnings("rawtypes") final CompletableFuture[] futureArray = futureList.toArray(new CompletableFuture[futureList.size()]);
    return from(CompletableFuture.allOf(futureArray));
}

21. ConcurrentContainsKeyTest#testOnce()

Project: openjdk
File: ConcurrentContainsKeyTest.java
private static void testOnce(Object[] content, ConcurrentHashMap<Object, Object> m) {
    CountDownLatch s = new CountDownLatch(1);
    Supplier<Runnable> sr = () -> () -> {
        try {
            s.await();
        } catch (InterruptedException e) {
        }
        for (int i = 0; i < R * N; i++) {
            Object o = content[i % content.length];
            if (!m.containsKey(o)) {
                throw new AssociationFailure("CHM.containsKey failed: entry does not exist");
            }
        }
    };
    int ps = Runtime.getRuntime().availableProcessors();
    Stream<CompletableFuture> runners = IntStream.range(0, ps).mapToObj( i -> sr.get()).map(CompletableFuture::runAsync);
    CompletableFuture all = CompletableFuture.allOf(runners.toArray(CompletableFuture[]::new));
    // Trigger the runners to start checking key membership
    s.countDown();
    try {
        all.join();
    } catch (CompletionException e) {
        Throwable t = e.getCause();
        if (t instanceof AssociationFailure) {
            throw (AssociationFailure) t;
        } else {
            throw e;
        }
    }
}

22. ConcurrentAssociateTest#testOnce()

Project: openjdk
File: ConcurrentAssociateTest.java
private static void testOnce(String desc, BiConsumer<ConcurrentMap<Object, Object>, Object> associator) throws Throwable {
    ConcurrentHashMap<Object, Object> m = new ConcurrentHashMap<>();
    CountDownLatch s = new CountDownLatch(1);
    Supplier<Runnable> sr = () -> () -> {
        try {
            if (!s.await(TIMEOUT, TimeUnit.SECONDS)) {
                dumpTestThreads();
                throw new AssertionError("timed out");
            }
        } catch (InterruptedException e) {
        }
        for (int i = 0; i < N; i++) {
            Object o = new X();
            associator.accept(m, o);
            if (!m.containsKey(o)) {
                throw new AssociationFailure(desc + " failed: entry does not exist");
            }
        }
    };
    // Bound concurrency to avoid degenerate performance
    int ps = Math.min(Runtime.getRuntime().availableProcessors(), 8);
    Stream<CompletableFuture> runners = IntStream.range(0, ps).mapToObj( i -> sr.get()).map(CompletableFuture::runAsync);
    CompletableFuture all = CompletableFuture.allOf(runners.toArray(CompletableFuture[]::new));
    // Trigger the runners to start associating
    s.countDown();
    try {
        all.get(TIMEOUT, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
        dumpTestThreads();
        throw e;
    } catch (Throwable e) {
        dumpTestThreads();
        Throwable cause = e.getCause();
        if (cause instanceof AssociationFailure) {
            throw cause;
        }
        throw e;
    }
}

23. GCCloseableTest#setup()

Project: monsoon
File: GCCloseableTest.java
@Before
public void setup() {
    closed_ = new CompletableFuture<>();
    ref = new GCCloseable<>(new CloseableImpl(closed_));
}

24. BestPriceFinder#printPricesStream()

Project: Java8InAction
File: BestPriceFinder.java
public void printPricesStream(String product) {
    long start = System.nanoTime();
    CompletableFuture[] futures = findPricesStream(product).map( f -> f.thenAccept( s -> System.out.println(s + " (done in " + ((System.nanoTime() - start) / 1_000_000) + " msecs)"))).toArray( size -> new CompletableFuture[size]);
    CompletableFuture.allOf(futures).join();
    System.out.println("All shops have now responded in " + ((System.nanoTime() - start) / 1_000_000) + " msecs");
}

25. CompletableFutureComprehenderTest#testFromIteratorWithEmptyIterator()

Project: cyclops-react
File: CompletableFutureComprehenderTest.java
@Test
public void testFromIteratorWithEmptyIterator() throws ExecutionException, InterruptedException {
    CompletableFutureComprehender completableFutureComprehender = new CompletableFutureComprehender();
    List<String> strs = new ArrayList();
    CompletableFuture completableFuture = completableFutureComprehender.fromIterator(strs.iterator());
    Object o = completableFuture.get();
    Assert.assertNull(o);
}

26. CompletableFutureComprehenderTest#testFromIterator()

Project: cyclops-react
File: CompletableFutureComprehenderTest.java
@Test
public void testFromIterator() throws ExecutionException, InterruptedException {
    CompletableFutureComprehender completableFutureComprehender = new CompletableFutureComprehender();
    List<String> strs = Arrays.asList("a", "b", "c");
    CompletableFuture completableFuture = completableFutureComprehender.fromIterator(strs.iterator());
    Object o = completableFuture.get();
    Assert.assertEquals(o, "a");
}

27. ConnectionManager#close()

Project: copycat
File: ConnectionManager.java
/**
   * Closes the connection manager.
   *
   * @return A completable future to be completed once the connection manager is closed.
   */
public CompletableFuture<Void> close() {
    CompletableFuture[] futures = new CompletableFuture[connections.size()];
    int i = 0;
    for (Connection connection : connections.values()) {
        futures[i++] = connection.close();
    }
    return CompletableFuture.allOf(futures);
}

28. ClusterState#leave()

Project: copycat
File: ClusterState.java
/**
   * Leaves the cluster.
   */
@Override
public synchronized CompletableFuture<Void> leave() {
    if (leaveFuture != null)
        return leaveFuture;
    leaveFuture = new CompletableFuture<>();
    context.getThreadContext().executor().execute(() -> {
        // If a join attempt is still underway, cancel the join and complete the join future exceptionally.
        // The join future will be set to null once completed.
        cancelJoinTimer();
        if (joinFuture != null)
            joinFuture.completeExceptionally(new IllegalStateException("failed to join cluster"));
        // If there are no remote members to leave, simply transition the server to INACTIVE.
        if (getActiveMemberStates().isEmpty() && configuration.index() <= context.getCommitIndex()) {
            LOGGER.debug("{} - Single member cluster. Transitioning directly to inactive.", member().address());
            context.transition(CopycatServer.State.INACTIVE);
            leaveFuture.complete(null);
        } else {
            leave(leaveFuture);
        }
    });
    return leaveFuture.whenComplete(( result,  error) -> leaveFuture = null);
}

29. ClientConnection#connect()

Project: copycat
File: ClientConnection.java
/**
   * Connects to the cluster.
   */
private CompletableFuture<Connection> connect() {
    // If the address selector has been then reset the connection.
    if (selector.state() == AddressSelector.State.RESET && connection != null) {
        if (connectFuture != null)
            return connectFuture;
        CompletableFuture<Connection> future = new CompletableFuture<>();
        connectFuture = future;
        connection.close().whenComplete(( result,  error) -> connect(future));
        return connectFuture.whenComplete(( result,  error) -> connectFuture = null);
    }
    // If a connection was already established then use that connection.
    if (connection != null)
        return CompletableFuture.completedFuture(connection);
    // If a connection is currently being established then piggyback on the connect future.
    if (connectFuture != null)
        return connectFuture;
    // Create a new connect future and connect to the first server in the cluster.
    connectFuture = new CompletableFuture<>();
    connect(connectFuture);
    // Reset the connect future field once the connection is complete.
    return connectFuture.whenComplete(( result,  error) -> connectFuture = null);
}

30. UtilTest#setUp()

Project: apollo
File: UtilTest.java
@Before
public void setUp() throws Exception {
    future = SettableFuture.create();
    stage = new CompletableFuture<>();
}

31. EndpointInvocationHandlerTest#setUp()

Project: apollo
File: EndpointInvocationHandlerTest.java
@Before
public void setUp() throws Exception {
    handler = new EndpointInvocationHandler();
    Request requestMessage = Request.forUri("http://foo/bar").withService("nameless-registry");
    when(ongoingRequest.request()).thenReturn(requestMessage);
    when(requestContext.request()).thenReturn(requestMessage);
    future = new CompletableFuture<>();
}