Java Code Examples for java.util.concurrent.CompletableFuture#completeAsync()

The following examples show how to use java.util.concurrent.CompletableFuture#completeAsync() . 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
Source File: MultiExchange.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
CompletableFuture<U> multiResponseAsync() {
    CompletableFuture<Void> start = new MinimalFuture<>();
    CompletableFuture<HttpResponseImpl<T>> cf = responseAsync0(start);
    CompletableFuture<HttpResponse<T>> mainResponse =
            cf.thenApply((HttpResponseImpl<T> b) -> {
                  multiResponseHandler.onResponse(b);
                  return (HttpResponse<T>)b;
               });

    pushGroup.setMainResponse(mainResponse);
    // set up house-keeping related to multi-response
    mainResponse.thenAccept((r) -> {
        // All push promises received by now.
        pushGroup.noMorePushes(true);
    });
    CompletableFuture<U> res = multiResponseHandler.completion(pushGroup.groupResult(), pushGroup.pushesCF());
    start.completeAsync( () -> null, executor); // trigger execution
    return res;
}
 
Example 2
Source File: ExternalMessagingClient.java    From enmasse with Apache License 2.0 6 votes vote down vote up
public Future<Void> getLinkAttachedProbe() {
    Objects.requireNonNull(this.client);
    if (client.getLinkAttached() != null) {
        return client.getLinkAttached();
    } else {
        CompletableFuture<Void> defaultWait = new CompletableFuture<Void>();
        defaultWait.completeAsync(() -> {
            try {
                Thread.sleep(14000);
            } catch (Exception e) {
                LOGGER.error("Error in default wait for link attached", e);
            }
            return null;
        }, r -> new Thread(r).start());
        return defaultWait;
    }
}
 
Example 3
Source File: Stream.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Override
void completeResponse(Response r) {
    HttpResponseImpl.logResponse(r);
    pushCF.complete(r); // not strictly required for push API
    // start reading the body using the obtained BodyProcessor
    CompletableFuture<Void> start = new MinimalFuture<>();
    start.thenCompose( v -> readBodyAsync(getPushHandler(), false, getExchange().executor()))
        .whenComplete((T body, Throwable t) -> {
            if (t != null) {
                responseCF.completeExceptionally(t);
            } else {
                HttpResponseImpl<T> response = new HttpResponseImpl<>(r.request, r, body, getExchange());
                responseCF.complete(response);
            }
        });
    start.completeAsync(() -> null, getExchange().executor());
}
 
Example 4
Source File: Java9RequestContextAwareFutureTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void makeContextAwareCompletableFutureUsingCompleteAsync() throws Exception {
    final RequestContext context =
            ServiceRequestContext.builder(HttpRequest.of(HttpMethod.GET, "/")).build();
    final CompletableFuture<String> originalFuture = new CompletableFuture<>();
    final CompletableFuture<String> contextAwareFuture = context.makeContextAware(originalFuture);
    final CompletableFuture<String> resultFuture = contextAwareFuture.completeAsync(() -> "success");

    originalFuture.complete("success");
    assertThat(resultFuture.get()).isEqualTo("success");
}
 
Example 5
Source File: CompletableFutureUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void testDelay () throws Exception {
    Object input = new Object();
    CompletableFuture<Object> future = new CompletableFuture<>();
    future.completeAsync(() -> input, CompletableFuture.delayedExecutor(1, TimeUnit.SECONDS));
    
    Thread.sleep(100);
    
    assertFalse(future.isDone());
    
    Thread.sleep(1000);
    assertTrue(future.isDone());
    assertSame(input, future.get());
}
 
Example 6
Source File: PgConnectionPool.java    From postgres-async-driver with Apache License 2.0 5 votes vote down vote up
private void closeNextStatement(Iterator<PooledPgPreparedStatement> statementsSource, CompletableFuture<Void> onComplete) {
    if (statementsSource.hasNext()) {
        statementsSource.next().delegate.close()
                .thenAccept(v -> {
                    statementsSource.remove();
                    closeNextStatement(statementsSource, onComplete);
                })
                .exceptionally(th -> {
                    futuresExecutor.execute(() -> onComplete.completeExceptionally(th));
                    return null;
                });
    } else {
        onComplete.completeAsync(() -> null, futuresExecutor);
    }
}
 
Example 7
Source File: CompletableFutureTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * completeAsync with given executor completes exceptionally if
 * given supplier throws
 */
public void testCompleteAsync4() {
    CompletableFuture<Integer> f = new CompletableFuture<>();
    CFException ex = new CFException();
    ThreadExecutor executor = new ThreadExecutor();
    f.completeAsync(() -> {if (true) throw ex; return 1;}, executor);
    try {
        f.join();
        shouldThrow();
    } catch (CompletionException success) {}
    checkCompletedWithWrappedException(f, ex);
    assertEquals(1, executor.count.get());
}
 
Example 8
Source File: CompletableFutureTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * completeAsync with given executor completes with value of given supplier
 */
public void testCompleteAsync3() {
    for (Integer v1 : new Integer[] { 1, null })
{
    CompletableFuture<Integer> f = new CompletableFuture<>();
    ThreadExecutor executor = new ThreadExecutor();
    f.completeAsync(() -> v1, executor);
    assertSame(v1, f.join());
    checkCompletedNormally(f, v1);
    assertEquals(1, executor.count.get());
}}
 
Example 9
Source File: CompletableFutureTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * completeAsync completes exceptionally if given supplier throws
 */
public void testCompleteAsync2() {
    CompletableFuture<Integer> f = new CompletableFuture<>();
    CFException ex = new CFException();
    f.completeAsync(() -> {if (true) throw ex; return 1;});
    try {
        f.join();
        shouldThrow();
    } catch (CompletionException success) {}
    checkCompletedWithWrappedException(f, ex);
}
 
Example 10
Source File: CompletableFutureTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * completeAsync completes with value of given supplier
 */
public void testCompleteAsync() {
    for (Integer v1 : new Integer[] { 1, null })
{
    CompletableFuture<Integer> f = new CompletableFuture<>();
    f.completeAsync(() -> v1);
    f.join();
    checkCompletedNormally(f, v1);
}}
 
Example 11
Source File: Java9RequestContextAwareFutureTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void makeContextAwareCompletableFutureUsingCompleteAsyncWithExecutor() throws Exception {
    final ExecutorService executor = Executors.newFixedThreadPool(2);
    final RequestContext context =
            ServiceRequestContext.builder(HttpRequest.of(HttpMethod.GET, "/")).build();
    final CompletableFuture<String> originalFuture = new CompletableFuture<>();
    final CompletableFuture<String> contextAwareFuture = context.makeContextAware(originalFuture);
    final CompletableFuture<String> resultFuture = contextAwareFuture.completeAsync(() -> "success",
                                                                                    executor);

    originalFuture.complete("success");
    assertThat(resultFuture.get()).isEqualTo("success");
}
 
Example 12
Source File: CompletableFutureTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * completeAsync with given executor completes exceptionally if
 * given supplier throws
 */
public void testCompleteAsync4() {
    CompletableFuture<Integer> f = new CompletableFuture<>();
    CFException ex = new CFException();
    ThreadExecutor executor = new ThreadExecutor();
    f.completeAsync(() -> { throw ex; }, executor);
    try {
        f.join();
        shouldThrow();
    } catch (CompletionException success) {}
    checkCompletedWithWrappedException(f, ex);
    assertEquals(1, executor.count.get());
}
 
Example 13
Source File: CompletableFutureTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * completeAsync with given executor completes with value of given supplier
 */
public void testCompleteAsync3() {
    for (Integer v1 : new Integer[] { 1, null })
{
    CompletableFuture<Integer> f = new CompletableFuture<>();
    ThreadExecutor executor = new ThreadExecutor();
    f.completeAsync(() -> v1, executor);
    assertSame(v1, f.join());
    checkCompletedNormally(f, v1);
    assertEquals(1, executor.count.get());
}}
 
Example 14
Source File: CompletableFutureTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * completeAsync completes exceptionally if given supplier throws
 */
public void testCompleteAsync2() {
    CompletableFuture<Integer> f = new CompletableFuture<>();
    CFException ex = new CFException();
    f.completeAsync(() -> { throw ex; });
    try {
        f.join();
        shouldThrow();
    } catch (CompletionException success) {}
    checkCompletedWithWrappedException(f, ex);
}
 
Example 15
Source File: CompletableFutureTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * completeAsync completes with value of given supplier
 */
public void testCompleteAsync() {
    for (Integer v1 : new Integer[] { 1, null })
{
    CompletableFuture<Integer> f = new CompletableFuture<>();
    f.completeAsync(() -> v1);
    f.join();
    checkCompletedNormally(f, v1);
}}
 
Example 16
Source File: MinimalFuture.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static <U> CompletableFuture<U> supply(ExceptionalSupplier<U> supplier, Executor executor) {
    CompletableFuture<U> cf = new MinimalFuture<>();
    cf.completeAsync( () -> {
        try {
            return supplier.get();
        } catch (Throwable ex) {
            throw new CompletionException(ex);
        }
    }, executor);
    return cf;
}
 
Example 17
Source File: MultiExchange.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public CompletableFuture<HttpResponseImpl<T>> responseAsync() {
    CompletableFuture<Void> start = new MinimalFuture<>();
    CompletableFuture<HttpResponseImpl<T>> cf = responseAsync0(start);
    start.completeAsync( () -> null, executor); // trigger execution
    return cf;
}
 
Example 18
Source File: PgConnectionPool.java    From postgres-async-driver with Apache License 2.0 4 votes vote down vote up
@Override
public CompletableFuture<Connection> getConnection() {
    CompletableFuture<Connection> uponAvailable = new CompletableFuture<>();

    lock.lock();
    try {
        if (closed) {
            futuresExecutor.execute(() -> uponAvailable.completeExceptionally(new SqlException("Connection pool is closed")));
        } else {
            Connection connection = connections.poll();
            if (connection != null) {
                uponAvailable.completeAsync(() -> connection, futuresExecutor);
            } else {
                if (tryIncreaseSize()) {
                    new PooledPgConnection(new PgConnection(toStream.apply(futuresExecutor), dataConverter, encoding))
                            .connect(username, password, database)
                            .thenApply(pooledConnection -> {
                                if (validationQuery != null && !validationQuery.isBlank()) {
                                    return pooledConnection.completeScript(validationQuery)
                                            .handle((rss, th) -> {
                                                if (th != null) {
                                                    return ((PooledPgConnection) pooledConnection).delegate.close()
                                                            .thenApply(v -> CompletableFuture.<Connection>failedFuture(th))
                                                            .thenCompose(Function.identity());
                                                } else {
                                                    return CompletableFuture.completedFuture(pooledConnection);
                                                }
                                            })
                                            .thenCompose(Function.identity());
                                } else {
                                    return CompletableFuture.completedFuture(pooledConnection);
                                }
                            })
                            .thenCompose(Function.identity())
                            .thenAccept(pooledConnection -> uponAvailable.completeAsync(() -> pooledConnection, futuresExecutor))
                            .exceptionally(th -> {
                                lock.lock();
                                try {
                                    size--;
                                    futuresExecutor.execute(() -> uponAvailable.completeExceptionally(th));
                                    return null;
                                } finally {
                                    lock.unlock();
                                }
                            });
                } else {
                    // Pool is full now and all connections are busy
                    subscribers.offer(uponAvailable);
                }
            }
        }
    } finally {
        lock.unlock();
    }

    return uponAvailable;
}