Example usage for java.util.concurrent CompletableFuture join

List of usage examples for java.util.concurrent CompletableFuture join

Introduction

In this page you can find the example usage for java.util.concurrent CompletableFuture join.

Prototype

@SuppressWarnings("unchecked")
public T join() 

Source Link

Document

Returns the result value when complete, or throws an (unchecked) exception if completed exceptionally.

Usage

From source file:org.apache.pulsar.io.kafka.connect.PulsarOffsetBackingStore.java

@Override
public void start() {
    try {/* w w w  .  j av a  2  s  .  c  o  m*/
        client = PulsarClient.builder().serviceUrl(serviceUrl).build();
        log.info("Successfully created pulsar client to {}", serviceUrl);
        producer = client.newProducer(Schema.BYTES).topic(topic).create();
        log.info("Successfully created producer to produce updates to topic {}", topic);
        reader = client.newReader(Schema.BYTES).topic(topic).startMessageId(MessageId.earliest).create();
        log.info("Successfully created reader to replay updates from topic {}", topic);
        CompletableFuture<Void> endFuture = new CompletableFuture<>();
        readToEnd(endFuture);
        endFuture.join();
    } catch (PulsarClientException e) {
        log.error("Failed to create pulsar client to cluster at {}", serviceUrl, e);
        throw new RuntimeException("Failed to create pulsar client to cluster at " + serviceUrl, e);
    }
}

From source file:org.apache.pulsar.tests.DockerUtils.java

public static String runCommand(DockerClient docker, String containerId, String... cmd) {
    CompletableFuture<Boolean> future = new CompletableFuture<>();
    String execid = docker.execCreateCmd(containerId).withCmd(cmd).withAttachStderr(true).withAttachStdout(true)
            .exec().getId();//from w  ww . j  a v a 2 s .  co m
    String cmdString = Arrays.stream(cmd).collect(Collectors.joining(" "));
    StringBuffer output = new StringBuffer();
    docker.execStartCmd(execid).withDetach(false).exec(new ResultCallback<Frame>() {
        @Override
        public void close() {
        }

        @Override
        public void onStart(Closeable closeable) {
            LOG.info("DOCKER.exec({}:{}): Executing...", containerId, cmdString);
        }

        @Override
        public void onNext(Frame object) {
            LOG.info("DOCKER.exec({}:{}): {}", containerId, cmdString, object);
            output.append(new String(object.getPayload()));
        }

        @Override
        public void onError(Throwable throwable) {
            future.completeExceptionally(throwable);
        }

        @Override
        public void onComplete() {
            LOG.info("DOCKER.exec({}:{}): Done", containerId, cmdString);
            future.complete(true);
        }
    });
    future.join();

    InspectExecResponse resp = docker.inspectExecCmd(execid).exec();
    while (resp.isRunning()) {
        try {
            Thread.sleep(200);
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(ie);
        }
        resp = docker.inspectExecCmd(execid).exec();
    }
    int retCode = resp.getExitCode();
    if (retCode != 0) {
        throw new RuntimeException(
                String.format("cmd(%s) failed on %s with exitcode %d", cmdString, containerId, retCode));
    } else {
        LOG.info("DOCKER.exec({}:{}): completed with {}", containerId, cmdString, retCode);
    }
    return output.toString();
}

From source file:org.apache.pulsar.tests.integration.utils.DockerUtils.java

public static ContainerExecResult runCommand(DockerClient docker, String containerId, String... cmd)
        throws ContainerExecException {
    CompletableFuture<Boolean> future = new CompletableFuture<>();
    String execid = docker.execCreateCmd(containerId).withCmd(cmd).withAttachStderr(true).withAttachStdout(true)
            .exec().getId();/*w ww  .jav a  2 s  . c  om*/
    String cmdString = Arrays.stream(cmd).collect(Collectors.joining(" "));
    StringBuilder stdout = new StringBuilder();
    StringBuilder stderr = new StringBuilder();
    docker.execStartCmd(execid).withDetach(false).exec(new ResultCallback<Frame>() {
        @Override
        public void close() {
        }

        @Override
        public void onStart(Closeable closeable) {
            LOG.info("DOCKER.exec({}:{}): Executing...", containerId, cmdString);
        }

        @Override
        public void onNext(Frame object) {
            LOG.info("DOCKER.exec({}:{}): {}", containerId, cmdString, object);
            if (StreamType.STDOUT == object.getStreamType()) {
                stdout.append(new String(object.getPayload(), UTF_8));
            } else if (StreamType.STDERR == object.getStreamType()) {
                stderr.append(new String(object.getPayload(), UTF_8));
            }
        }

        @Override
        public void onError(Throwable throwable) {
            future.completeExceptionally(throwable);
        }

        @Override
        public void onComplete() {
            LOG.info("DOCKER.exec({}:{}): Done", containerId, cmdString);
            future.complete(true);
        }
    });
    future.join();

    InspectExecResponse resp = docker.inspectExecCmd(execid).exec();
    while (resp.isRunning()) {
        try {
            Thread.sleep(200);
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(ie);
        }
        resp = docker.inspectExecCmd(execid).exec();
    }
    int retCode = resp.getExitCode();
    ContainerExecResult result = ContainerExecResult.of(retCode, stdout.toString(), stderr.toString());
    LOG.info("DOCKER.exec({}:{}): completed with {}", containerId, cmdString, retCode);

    if (retCode != 0) {
        throw new ContainerExecException(cmdString, containerId, result);
    }
    return result;
}

From source file:org.apache.pulsar.tests.integration.utils.DockerUtils.java

public static ContainerExecResultBytes runCommandWithRawOutput(DockerClient docker, String containerId,
        String... cmd) throws ContainerExecException {
    CompletableFuture<Boolean> future = new CompletableFuture<>();
    String execid = docker.execCreateCmd(containerId).withCmd(cmd).withAttachStderr(true).withAttachStdout(true)
            .exec().getId();//from   w  w w. j av a 2s .c  om
    String cmdString = Arrays.stream(cmd).collect(Collectors.joining(" "));
    ByteBuf stdout = Unpooled.buffer();
    ByteBuf stderr = Unpooled.buffer();
    docker.execStartCmd(execid).withDetach(false).exec(new ResultCallback<Frame>() {
        @Override
        public void close() {
        }

        @Override
        public void onStart(Closeable closeable) {
            LOG.info("DOCKER.exec({}:{}): Executing...", containerId, cmdString);
        }

        @Override
        public void onNext(Frame object) {
            if (StreamType.STDOUT == object.getStreamType()) {
                stdout.writeBytes(object.getPayload());
            } else if (StreamType.STDERR == object.getStreamType()) {
                stderr.writeBytes(object.getPayload());
            }
        }

        @Override
        public void onError(Throwable throwable) {
            future.completeExceptionally(throwable);
        }

        @Override
        public void onComplete() {
            LOG.info("DOCKER.exec({}:{}): Done", containerId, cmdString);
            future.complete(true);
        }
    });
    future.join();

    InspectExecResponse resp = docker.inspectExecCmd(execid).exec();
    while (resp.isRunning()) {
        try {
            Thread.sleep(200);
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(ie);
        }
        resp = docker.inspectExecCmd(execid).exec();
    }
    int retCode = resp.getExitCode();

    byte[] stdoutBytes = new byte[stdout.readableBytes()];
    stdout.readBytes(stdoutBytes);
    byte[] stderrBytes = new byte[stderr.readableBytes()];
    stderr.readBytes(stderrBytes);

    ContainerExecResultBytes result = ContainerExecResultBytes.of(retCode, stdoutBytes, stderrBytes);
    LOG.info("DOCKER.exec({}:{}): completed with {}", containerId, cmdString, retCode);

    if (retCode != 0) {
        throw new ContainerExecException(cmdString, containerId, null);
    }
    return result;
}

From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutorPerformanceTest.java

@BenchmarkOptions(benchmarkRounds = DEFAULT_BENCHMARK_ROUNDS, warmupRounds = DEFAULT_WARMUP_ROUNDS, concurrency = BenchmarkOptions.CONCURRENCY_SEQUENTIAL)
@LoadGraphWith(LoadGraphWith.GraphData.GRATEFUL)
@Test/*from   w ww .  j  a v  a  2s.  co  m*/
public void executorEval() throws Exception {
    final Map<String, Object> params = new HashMap<>();
    params.put("g", g);

    final String traversal = generator.generateGremlin();
    final int resultsToNextOut = rand.nextInt(512) + 1;
    final String nextedTraversal = traversal + ".next(" + resultsToNextOut + ")";
    final CompletableFuture<Object> future1 = gremlinExecutor.eval(nextedTraversal, params);
    future1.join();
}

From source file:org.eclipse.jdt.ls.core.internal.handlers.JDTLanguageServer.java

@Override
public CompletableFuture<Either<List<CompletionItem>, CompletionList>> completion(CompletionParams position) {
    logInfo(">> document/completion");
    CompletionHandler handler = new CompletionHandler();
    final IProgressMonitor[] monitors = new IProgressMonitor[1];
    CompletableFuture<Either<List<CompletionItem>, CompletionList>> result = computeAsync((monitor) -> {
        monitors[0] = monitor;//from   ww  w. jav  a  2s  . com
        if (Boolean.getBoolean(JAVA_LSP_JOIN_ON_COMPLETION)) {
            waitForLifecycleJobs(monitor);
        }
        return handler.completion(position, monitor);
    });
    result.join();
    if (monitors[0].isCanceled()) {
        result.cancel(true);
    }
    return result;
}

From source file:org.eclipse.jdt.ls.core.internal.handlers.JDTLanguageServer.java

@Override
public CompletableFuture<CompletionItem> resolveCompletionItem(CompletionItem unresolved) {
    logInfo(">> document/resolveCompletionItem");
    CompletionResolveHandler handler = new CompletionResolveHandler(preferenceManager);
    final IProgressMonitor[] monitors = new IProgressMonitor[1];
    CompletableFuture<CompletionItem> result = computeAsync((monitor) -> {
        monitors[0] = monitor;//from w  w  w  .j av  a2 s.c o  m
        if ((Boolean.getBoolean(JAVA_LSP_JOIN_ON_COMPLETION))) {
            waitForLifecycleJobs(monitor);
        }
        return handler.resolve(unresolved, monitor);
    });
    result.join();
    if (monitors[0].isCanceled()) {
        result.cancel(true);
    }
    return result;
}

From source file:org.springframework.cloud.sleuth.instrument.async.issues.issue410.Issue410Tests.java

public Span completableFutures() throws ExecutionException, InterruptedException {
    log.info("This task is running with completable future");
    CompletableFuture<Span> span1 = CompletableFuture.supplyAsync(() -> {
        AsyncTask.log.info("First completable future");
        return AsyncTask.this.tracer.getCurrentSpan();
    }, AsyncTask.this.executor);
    CompletableFuture<Span> span2 = CompletableFuture.supplyAsync(() -> {
        AsyncTask.log.info("Second completable future");
        return AsyncTask.this.tracer.getCurrentSpan();
    }, AsyncTask.this.executor);
    CompletableFuture<Span> response = CompletableFuture.allOf(span1, span2).thenApply(ignoredVoid -> {
        AsyncTask.log.info("Third completable future");
        Span joinedSpan1 = span1.join();
        Span joinedSpan2 = span2.join();
        then(joinedSpan2).isNotNull();/*from  w w w  . j  a  va2 s . c o m*/
        then(joinedSpan1).hasTraceIdEqualTo(joinedSpan2.getTraceId());
        AsyncTask.log.info("TraceIds are correct");
        return joinedSpan2;
    });
    this.span.set(response.get());
    return this.span.get();
}

From source file:org.springframework.cloud.sleuth.instrument.async.issues.issue410.Issue410Tests.java

public Span taskScheduler() throws ExecutionException, InterruptedException {
    log.info("This task is running with completable future");
    CompletableFuture<Span> span1 = CompletableFuture.supplyAsync(() -> {
        AsyncTask.log.info("First completable future");
        return AsyncTask.this.tracer.getCurrentSpan();
    }, new LazyTraceExecutor(AsyncTask.this.beanFactory, AsyncTask.this.taskScheduler));
    CompletableFuture<Span> span2 = CompletableFuture.supplyAsync(() -> {
        AsyncTask.log.info("Second completable future");
        return AsyncTask.this.tracer.getCurrentSpan();
    }, new LazyTraceExecutor(AsyncTask.this.beanFactory, AsyncTask.this.taskScheduler));
    CompletableFuture<Span> response = CompletableFuture.allOf(span1, span2).thenApply(ignoredVoid -> {
        AsyncTask.log.info("Third completable future");
        Span joinedSpan1 = span1.join();
        Span joinedSpan2 = span2.join();
        then(joinedSpan2).isNotNull();/*from  w w  w. j a  v  a  2 s  . co m*/
        then(joinedSpan1).hasTraceIdEqualTo(joinedSpan2.getTraceId());
        AsyncTask.log.info("TraceIds are correct");
        return joinedSpan2;
    });
    this.span.set(response.get());
    return this.span.get();
}

From source file:ru.histone.v2.evaluator.Evaluator.java

private CompletionStage<EvalNode> processNonMapValue(ExpAstNode expNode, Context context) {
    if (expNode.size() == 4) {
        return CompletableFuture.completedFuture(EmptyEvalNode.INSTANCE);
    }//from w  w  w.  j  a v a2 s .co m
    int i = 0;
    ExpAstNode expressionNode = expNode.getNode(i + 4);
    ExpAstNode bodyNode = expNode.getNode(i + 5);
    while (bodyNode != null) {
        CompletableFuture<EvalNode> conditionFuture = evaluateNode(expressionNode, context);
        EvalNode conditionNode = conditionFuture.join();
        if (nodeAsBoolean(conditionNode)) {
            return evaluateNode(bodyNode, context);
        }
        i++;
        expressionNode = expNode.getNode(i + 4);
        bodyNode = expNode.getNode(i + 5);
    }
    if (expressionNode != null) {
        return evaluateNode(expressionNode, context);
    }

    return CompletableFuture.completedFuture(EmptyEvalNode.INSTANCE);
}