Example usage for java.util.concurrent CompletableFuture runAsync

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

Introduction

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

Prototype

public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor) 

Source Link

Document

Returns a new CompletableFuture that is asynchronously completed by a task running in the given executor after it runs the given action.

Usage

From source file:io.pravega.controller.server.eventProcessor.ControllerEventProcessors.java

private CompletableFuture<Void> handleOrphanedReaders(
        final EventProcessorGroup<? extends ControllerEvent> group, final Supplier<Set<String>> processes) {
    return withRetriesAsync(() -> CompletableFuture.supplyAsync(() -> {
        try {//from  w ww.ja  v a  2  s . c  o m
            return group.getProcesses();
        } catch (CheckpointStoreException e) {
            if (e.getType().equals(CheckpointStoreException.Type.NoNode)) {
                return Collections.<String>emptySet();
            }
            throw new CompletionException(e);
        }
    }, executor), RETRYABLE_PREDICATE, Integer.MAX_VALUE, executor)
            .thenComposeAsync(groupProcesses -> withRetriesAsync(() -> CompletableFuture.supplyAsync(() -> {
                try {
                    return new ImmutablePair<>(processes.get(), groupProcesses);
                } catch (Exception e) {
                    log.error(String.format("Error fetching current processes%s", group.toString()), e);
                    throw new CompletionException(e);
                }
            }, executor), RETRYABLE_PREDICATE, Integer.MAX_VALUE, executor)).thenComposeAsync(pair -> {
                Set<String> activeProcesses = pair.getLeft();
                Set<String> registeredProcesses = pair.getRight();

                if (registeredProcesses == null || registeredProcesses.isEmpty()) {
                    return CompletableFuture.completedFuture(null);
                }

                if (activeProcesses != null) {
                    registeredProcesses.removeAll(activeProcesses);
                }

                List<CompletableFuture<Void>> futureList = new ArrayList<>();
                for (String process : registeredProcesses) {
                    futureList.add(withRetriesAsync(() -> CompletableFuture.runAsync(() -> {
                        try {
                            group.notifyProcessFailure(process);
                        } catch (CheckpointStoreException e) {
                            log.error(String.format(
                                    "Error notifying failure of process=%s in event processor group %s",
                                    process, group.toString()), e);
                            throw new CompletionException(e);
                        }
                    }, executor), RETRYABLE_PREDICATE, Integer.MAX_VALUE, executor));
                }

                return FutureHelpers.allOf(futureList);
            });
}

From source file:io.sqp.client.impl.SqpConnectionImpl.java

CompletableFuture<Void> send(Reader reader) {
    int bufSize = Math.min(MAX_MSG_BUFFER_SIZE, _session.getMaxTextMessageBufferSize());
    return CompletableFuture.runAsync(() -> {
        char[] buffer = new char[bufSize];
        int bytesRead;
        try (Writer output = _endpoint.getSendWriter()) {
            while ((bytesRead = reader.read(buffer)) > 0) {
                output.write(buffer, 0, bytesRead);
            }// w  ww .j a  va 2 s  .c om
        } catch (IOException e) {
            throw new CompletionException(new SqpIOException(e));
        }
    }, _sendingService).exceptionally(new FailHandler(this));
}

From source file:org.apache.storm.localizer.AsyncLocalizer.java

private CompletableFuture<Void> downloadOrUpdate(LocallyCachedBlob... blobs) {
    CompletableFuture<Void>[] all = new CompletableFuture[blobs.length];
    for (int i = 0; i < blobs.length; i++) {
        final LocallyCachedBlob blob = blobs[i];
        all[i] = CompletableFuture.runAsync(() -> {
            LOG.debug("STARTING download of {}", blob);
            try (ClientBlobStore blobStore = ServerUtils.getClientBlobStoreForSupervisor(conf)) {
                boolean done = false;
                long failures = 0;
                while (!done) {
                    try {
                        synchronized (blob) {
                            long localVersion = blob.getLocalVersion();
                            long remoteVersion = blob.getRemoteVersion(blobStore);
                            if (localVersion != remoteVersion) {
                                try {
                                    long newVersion = blob.downloadToTempLocation(blobStore);
                                    blob.informAllOfChangeAndWaitForConsensus();
                                    blob.commitNewVersion(newVersion);
                                    blob.informAllChangeComplete();
                                } finally {
                                    blob.cleanupOrphanedData();
                                }//from  w w w  .  j a  v a 2  s  .c  o  m
                            }
                        }
                        done = true;
                    } catch (Exception e) {
                        failures++;
                        if (failures > blobDownloadRetries) {
                            throw new RuntimeException("Could not download...", e);
                        }
                        LOG.warn("Failed to download blob {} will try again in {} ms", blob,
                                ATTEMPTS_INTERVAL_TIME, e);
                        Utils.sleep(ATTEMPTS_INTERVAL_TIME);
                    }
                }
            }
            LOG.debug("FINISHED download of {}", blob);
        }, execService);
    }
    return CompletableFuture.allOf(all);
}

From source file:org.apache.streams.cassandra.CassandraPersistReader.java

@Override
public void startStream() {
    LOGGER.debug("startStream");
    CassandraPersistReaderTask readerTask = new CassandraPersistReaderTask(this);

    CompletableFuture.runAsync(readerTask, executor);

    try {/*  ww w  .j  av  a  2 s .  c o m*/
        if (readerTaskFuture.get()) {
            executor.shutdown();
        }
    } catch (InterruptedException ex) {
        LOGGER.trace("Interrupt", ex);
    } catch (ExecutionException ex) {
        LOGGER.trace("Execution exception", ex);
    }
}

From source file:org.jboss.pnc.environment.openshift.OpenshiftStartedEnvironment.java

private void createEnvironment() {

    List<CompletableFuture<Void>> trackCreationFutures = new ArrayList<>();

    String randString = RandomUtils.randString(6);//note the 24 char limit
    buildAgentContextPath = "pnc-ba-" + randString;

    runtimeProperties.put("pod-name", "pnc-ba-pod-" + randString);
    runtimeProperties.put("service-name", "pnc-ba-service-" + randString);
    runtimeProperties.put("ssh-service-name", "pnc-ba-ssh-" + randString);
    runtimeProperties.put("route-name", "pnc-ba-route-" + randString);
    runtimeProperties.put("route-path", "/" + buildAgentContextPath);
    runtimeProperties.put("buildAgentContextPath", "/" + buildAgentContextPath);

    initDebug();//  w w  w  .  j a va  2  s.c om

    ModelNode podConfigurationNode = createModelNode(
            Configurations.getContentAsString(Resource.PNC_BUILDER_POD, openshiftBuildAgentConfig),
            runtimeProperties);
    pod = new Pod(podConfigurationNode, client,
            ResourcePropertiesRegistry.getInstance().get(OSE_API_VERSION, ResourceKind.POD));
    pod.setNamespace(environmentConfiguration.getPncNamespace());
    Runnable createPod = () -> {
        try {
            client.create(pod, pod.getNamespace());
        } catch (Throwable e) {
            logger.error("Cannot create pod.", e);
            throw e;
        }
    };
    creatingPod = Optional.of(CompletableFuture.runAsync(createPod, executor));
    trackCreationFutures.add(creatingPod.get());

    ModelNode serviceConfigurationNode = createModelNode(
            Configurations.getContentAsString(Resource.PNC_BUILDER_SERVICE, openshiftBuildAgentConfig),
            runtimeProperties);
    service = new Service(serviceConfigurationNode, client,
            ResourcePropertiesRegistry.getInstance().get(OSE_API_VERSION, ResourceKind.SERVICE));
    service.setNamespace(environmentConfiguration.getPncNamespace());
    Runnable createService = () -> {
        try {
            client.create(service, service.getNamespace());
        } catch (Throwable e) {
            logger.error("Cannot create service.", e);
            throw e;
        }
    };
    creatingService = Optional.of(CompletableFuture.runAsync(createService, executor));
    trackCreationFutures.add(creatingService.get());

    if (createRoute) {
        ModelNode routeConfigurationNode = createModelNode(
                Configurations.getContentAsString(Resource.PNC_BUILDER_ROUTE, openshiftBuildAgentConfig),
                runtimeProperties);
        route = new Route(routeConfigurationNode, client,
                ResourcePropertiesRegistry.getInstance().get(OSE_API_VERSION, ResourceKind.ROUTE));
        route.setNamespace(environmentConfiguration.getPncNamespace());
        Runnable createRoute = () -> {
            try {
                client.create(route, route.getNamespace());
            } catch (Throwable e) {
                logger.error("Cannot create route.", e);
                throw e;
            }
        };
        creatingRoute = Optional.of(CompletableFuture.runAsync(createRoute, executor));
        trackCreationFutures.add(creatingRoute.get());
    }
    gaugeMetric.ifPresent(g -> g.incrementMetric(METRICS_POD_STARTED_ATTEMPTED_KEY));
}