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) 

Source Link

Document

Returns a new CompletableFuture that is asynchronously completed by a task running in the ForkJoinPool#commonPool() after it runs the given action.

Usage

From source file:io.pravega.test.system.framework.RemoteSequential.java

@Override
public CompletableFuture<Void> startTestExecution(Method testMethod) {

    log.debug("Starting test execution for method: {}", testMethod);

    String className = testMethod.getDeclaringClass().getName();
    String methodName = testMethod.getName();
    String jobId = (methodName + ".testJob").toLowerCase(); //All jobIds should have lowercase for metronome.

    return CompletableFuture.runAsync(() -> {
        CLIENT.createJob(newJob(jobId, className, methodName));
        Response response = CLIENT.triggerJobRun(jobId);
        if (response.status() != CREATED.code()) {
            throw new TestFrameworkException(TestFrameworkException.Type.ConnectionFailed,
                    "Error while starting " + "test " + testMethod);
        }//from w ww  .  j a  v  a 2s  .c  o m
    }).thenCompose(v2 -> waitForJobCompletion(jobId)).<Void>thenApply(v1 -> {
        if (CLIENT.getJob(jobId).getHistory().getFailureCount() != 0) {
            throw new AssertionError("Test failed, detailed logs can be found at "
                    + "https://MasterIP/mesos, under metronome framework tasks. MethodName: " + methodName);
        }
        return null;
    }).whenComplete((v, ex) -> {
        deleteJob(jobId); //deletejob once execution is complete.
        if (ex != null) {
            log.error("Error while executing the test. ClassName: {}, MethodName: {}", className, methodName);

        }
    });
}

From source file:com.microsoft.azure.servicebus.samples.receiveloop.ReceiveLoop.java

CompletableFuture receiveMessagesAsync(IMessageReceiver receiver) {

    CompletableFuture currentTask = new CompletableFuture();

    try {/*w  ww.j  av a  2  s .com*/
        CompletableFuture.runAsync(() -> {
            while (!currentTask.isCancelled()) {
                try {
                    IMessage message = receiver.receive(Duration.ofSeconds(60));
                    if (message != null) {
                        // receives message is passed to callback
                        if (message.getLabel() != null && message.getContentType() != null
                                && message.getLabel().contentEquals("Scientist")
                                && message.getContentType().contentEquals("application/json")) {

                            byte[] body = message.getBody();
                            Map scientist = GSON.fromJson(new String(body, UTF_8), Map.class);

                            System.out.printf(
                                    "\n\t\t\t\tMessage received: \n\t\t\t\t\t\tMessageId = %s, \n\t\t\t\t\t\tSequenceNumber = %s, \n\t\t\t\t\t\tEnqueuedTimeUtc = %s,"
                                            + "\n\t\t\t\t\t\tExpiresAtUtc = %s, \n\t\t\t\t\t\tContentType = \"%s\",  \n\t\t\t\t\t\tContent: [ firstName = %s, name = %s ]\n",
                                    message.getMessageId(), message.getSequenceNumber(),
                                    message.getEnqueuedTimeUtc(), message.getExpiresAtUtc(),
                                    message.getContentType(),
                                    scientist != null ? scientist.get("firstName") : "",
                                    scientist != null ? scientist.get("name") : "");
                        }
                        receiver.completeAsync(message.getLockToken());
                    }
                } catch (Exception e) {
                    currentTask.completeExceptionally(e);
                }
            }
            currentTask.complete(null);
        });
        return currentTask;
    } catch (Exception e) {
        currentTask.completeExceptionally(e);
    }
    return currentTask;
}

From source file:com.microsoft.azure.servicebus.samples.messagebrowse.MessageBrowse.java

CompletableFuture peekMessagesAsync(IMessageReceiver receiver) {

    CompletableFuture currentTask = new CompletableFuture();
    try {//from  w ww .  j  av  a2  s.  c o m
        CompletableFuture.runAsync(() -> {
            while (!currentTask.isCancelled()) {
                try {
                    IMessage message = receiver.peek();
                    if (message != null) {
                        // receives message is passed to callback
                        if (message.getLabel() != null && message.getContentType() != null
                                && message.getLabel().contentEquals("Scientist")
                                && message.getContentType().contentEquals("application/json")) {

                            byte[] body = message.getBody();
                            Map scientist = GSON.fromJson(new String(body, UTF_8), Map.class);

                            System.out.printf(
                                    "\n\t\t\t\tMessage received: \n\t\t\t\t\t\tMessageId = %s, \n\t\t\t\t\t\tSequenceNumber = %s, \n\t\t\t\t\t\tEnqueuedTimeUtc = %s,"
                                            + "\n\t\t\t\t\t\tExpiresAtUtc = %s, \n\t\t\t\t\t\tContentType = \"%s\",  \n\t\t\t\t\t\tContent: [ firstName = %s, name = %s ]\n",
                                    message.getMessageId(), message.getSequenceNumber(),
                                    message.getEnqueuedTimeUtc(), message.getExpiresAtUtc(),
                                    message.getContentType(),
                                    scientist != null ? scientist.get("firstName") : "",
                                    scientist != null ? scientist.get("name") : "");
                        } else {
                            currentTask.complete(null);
                        }
                    }
                } catch (Exception e) {
                    currentTask.completeExceptionally(e);
                }
            }
            if (!currentTask.isCancelled()) {
                currentTask.complete(null);
            }
        });
        return currentTask;
    } catch (Exception e) {
        currentTask.completeExceptionally(e);
    }
    return currentTask;
}

From source file:ai.grakn.engine.backgroundtasks.InMemoryTaskManager.java

public CompletableFuture completableFuture(String taskId) {
    if (!instantiatedTasks.containsKey(taskId)) {
        return null;
    }//from   ww  w . ja  v  a 2s. c  o m

    try {
        return CompletableFuture.runAsync(() -> {
            try {
                instantiatedTasks.get(taskId).getKey().get();
            } catch (InterruptedException | ExecutionException e) {
                throw new RuntimeException(e);
            }
        });
    } catch (Throwable t) {
        LOG.error(getFullStackTrace(t));
        throw new RuntimeException(t);
    }
}

From source file:ai.grakn.engine.backgroundtasks.distributed.DistributedTaskManager.java

@Override
public CompletableFuture completableFuture(String taskId) {
    return CompletableFuture.runAsync(() -> {

        while (true) {
            TaskStatus status = zkStorage.getState(taskId).status();
            if (status == COMPLETED || status == FAILED || status == STOPPED) {
                break;
            }/*from  w  w  w  .  j  a  va  2 s .c  o m*/

            try {
                Thread.sleep(5000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

From source file:ai.grakn.engine.backgroundtasks.standalone.StandaloneTaskManager.java

public CompletableFuture completableFuture(String taskId) {
    if (!instantiatedTasks.containsKey(taskId)) {
        return null;
    }/*from   w ww. ja va 2  s.c o  m*/

    try {
        return CompletableFuture.runAsync(() -> {
            try {
                while (true) {
                    TaskState state = storage().getState(taskId);
                    if (state.status().equals(COMPLETED) || state.status().equals(FAILED)) {
                        break;
                    }
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
    } catch (Throwable t) {
        LOG.error(getFullStackTrace(t));
        throw new RuntimeException(t);
    }
}

From source file:com.ikanow.aleph2.distributed_services.services.CoreDistributedServices.java

/** Guice-invoked constructor
 * @throws Exception //from w ww  .  j av a 2 s .  c o m
 */
@Inject
public CoreDistributedServices(DistributedServicesPropertyBean config_bean) throws Exception {

    final String connection_string = Optional.ofNullable(config_bean.zookeeper_connection())
            .orElse(DistributedServicesPropertyBean.__DEFAULT_ZOOKEEPER_CONNECTION);

    _config_bean = BeanTemplateUtils.clone(config_bean)
            .with(DistributedServicesPropertyBean::zookeeper_connection, connection_string).done();

    logger.info("Zookeeper connection_string=" + _config_bean.zookeeper_connection());

    // Else join akka cluster lazily, because often it's not required at all
    if (null != config_bean.application_name()) {
        joinAkkaCluster();
    }

    if (null != config_bean.broker_list()) {
        final String broker_list_string = config_bean.broker_list();
        KafkaUtils.setStandardKafkaProperties(_config_bean.zookeeper_connection(), broker_list_string,
                Optional.ofNullable(_config_bean.cluster_name())
                        .orElse(DistributedServicesPropertyBean.__DEFAULT_CLUSTER_NAME),
                Optional.empty());
        _initialized_kafka = new CompletableFuture<>();
        _initialized_kafka.complete(null);
        _initializing_kafka = false;
    } else { // Launch an async process to intialize kafka
        logger.info("Fetching Kafka broker_list from Zookeeper");
        _initialized_kafka = CompletableFuture.runAsync(() -> {
            try {
                final String broker_list = KafkaUtils.getBrokerListFromZookeeper(this.getCuratorFramework(),
                        Optional.empty(), _mapper);
                KafkaUtils
                        .setStandardKafkaProperties(_config_bean.zookeeper_connection(), broker_list,
                                Optional.ofNullable(_config_bean.cluster_name())
                                        .orElse(DistributedServicesPropertyBean.__DEFAULT_CLUSTER_NAME),
                                Optional.empty());
                logger.info("Kafka broker_list=" + broker_list);

                _kafka_zk_framework.set(KafkaUtils.getNewZkClient());
            } catch (Exception e) { // just use the default and hope:
                KafkaUtils
                        .setStandardKafkaProperties(_config_bean.zookeeper_connection(),
                                DistributedServicesPropertyBean.__DEFAULT_BROKER_LIST,
                                Optional.ofNullable(_config_bean.cluster_name())
                                        .orElse(DistributedServicesPropertyBean.__DEFAULT_CLUSTER_NAME),
                                Optional.empty());
            }
            _initializing_kafka = false;
        });
    }
}

From source file:com.docuware.dev.Extensions.ServiceConnection.java

/**
 * Disconnects the Instance//  w  w w .  j  a  v a2 s . c  o  m
 * @return  A Future, which disconnects the ServiceConnection
 */
public CompletableFuture disconnectAsync() {
    return CompletableFuture.runAsync(() -> {
        MethodInvocation.getAsync(serviceDescription, serviceDescription.getLinks(), "logout", null);
    });
}

From source file:sx.blah.discord.api.internal.DiscordWS.java

void connect() {
    WebSocketClient previous = wsClient; // for cleanup
    try {//from  w  ww  .  j av a2 s .  c  o  m
        wsClient = new WebSocketClient(new SslContextFactory());
        wsClient.setDaemon(true);
        wsClient.getPolicy().setMaxBinaryMessageSize(Integer.MAX_VALUE);
        wsClient.getPolicy().setMaxTextMessageSize(Integer.MAX_VALUE);
        wsClient.start();
        wsClient.connect(this, new URI(gateway), new ClientUpgradeRequest());
    } catch (Exception e) {
        Discord4J.LOGGER.error(LogMarkers.WEBSOCKET, "Encountered error while connecting websocket: ", e);
    } finally {
        if (previous != null) {
            CompletableFuture.runAsync(() -> {
                try {
                    previous.stop();
                } catch (Exception e) {
                    Discord4J.LOGGER.error(LogMarkers.WEBSOCKET, "Error while stopping previous websocket: ",
                            e);
                }
            });
        }
    }
}

From source file:io.pravega.controller.eventProcessor.impl.SerializedRequestHandlerTest.java

private void runBackgroundStreamProcessing(String streamName,
        SerializedRequestHandler<TestEvent> requestHandler, AtomicBoolean stop) {
    CompletableFuture.runAsync(() -> {
        while (!stop.get()) {
            TestEvent event = new TestEvent("scope", streamName, 0);
            event.complete();/*from   ww w  .  j  a va  2s  .c  o m*/
            Futures.await(requestHandler.process(event));
        }
    });
}