Example usage for java.util.concurrent CompletableFuture CompletableFuture

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

Introduction

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

Prototype

public CompletableFuture() 

Source Link

Document

Creates a new incomplete CompletableFuture.

Usage

From source file:org.apache.bookkeeper.client.BookieWriteLedgerTest.java

/**
 * Verify that LedgerHandleAdv cannnot handle addEntry without the entryId.
 *
 * @throws Exception// w ww  . j av a  2s. co m
 */
@Test
public void testNoAddEntryLedgerCreateAdv() throws Exception {

    ByteBuffer entry = ByteBuffer.allocate(4);
    entry.putInt(rng.nextInt(maxInt));
    entry.position(0);

    lh = bkc.createLedgerAdv(5, 3, 2, digestType, ledgerPassword);
    assertTrue(lh instanceof LedgerHandleAdv);

    try {
        lh.addEntry(entry.array());
        fail("using LedgerHandleAdv addEntry without entryId is forbidden");
    } catch (BKException e) {
        assertEquals(e.getCode(), BKException.Code.IllegalOpException);
    }

    try {
        lh.addEntry(entry.array(), 0, 4);
        fail("using LedgerHandleAdv addEntry without entryId is forbidden");
    } catch (BKException e) {
        assertEquals(e.getCode(), BKException.Code.IllegalOpException);
    }

    try {
        CompletableFuture<Object> done = new CompletableFuture<>();
        lh.asyncAddEntry(Unpooled.wrappedBuffer(entry.array()),
                (int rc, LedgerHandle lh1, long entryId, Object ctx) -> {
                    SyncCallbackUtils.finish(rc, null, done);
                }, null);
        done.get();
    } catch (ExecutionException ee) {
        assertTrue(ee.getCause() instanceof BKException);
        BKException e = (BKException) ee.getCause();
        assertEquals(e.getCode(), BKException.Code.IllegalOpException);
    }

    try {
        CompletableFuture<Object> done = new CompletableFuture<>();
        lh.asyncAddEntry(entry.array(), (int rc, LedgerHandle lh1, long entryId, Object ctx) -> {
            SyncCallbackUtils.finish(rc, null, done);
        }, null);
        done.get();
    } catch (ExecutionException ee) {
        assertTrue(ee.getCause() instanceof BKException);
        BKException e = (BKException) ee.getCause();
        assertEquals(e.getCode(), BKException.Code.IllegalOpException);
    }

    try {
        CompletableFuture<Object> done = new CompletableFuture<>();
        lh.asyncAddEntry(entry.array(), 0, 4, (int rc, LedgerHandle lh1, long entryId, Object ctx) -> {
            SyncCallbackUtils.finish(rc, null, done);
        }, null);
        done.get();
    } catch (ExecutionException ee) {
        assertTrue(ee.getCause() instanceof BKException);
        BKException e = (BKException) ee.getCause();
        assertEquals(e.getCode(), BKException.Code.IllegalOpException);
    }
    lh.close();
}

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

/**
 * Executors are only closed if they were not supplied externally in the
 * {@link org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor.Builder}
 *///from  www  .  j  ava2 s  .com
public CompletableFuture<Void> closeAsync() throws Exception {
    final CompletableFuture<Void> future = new CompletableFuture<>();

    new Thread(() -> {
        // leave pools running if they are supplied externally.  let the sender be responsible for shutting them down
        if (!suppliedExecutor) {
            executorService.shutdown();
            try {
                if (!executorService.awaitTermination(180000, TimeUnit.MILLISECONDS))
                    logger.warn("Timeout while waiting for ExecutorService of GremlinExecutor to shutdown.");
            } catch (InterruptedException ie) {
                logger.warn(
                        "ExecutorService on GremlinExecutor may not have shutdown properly as shutdown thread terminated early.");
            }
        }

        // calls to shutdown are idempotent so no problems calling it twice if the pool is shared
        if (!suppliedScheduledExecutor) {
            scheduledExecutorService.shutdown();
            try {
                if (!scheduledExecutorService.awaitTermination(180000, TimeUnit.MILLISECONDS))
                    logger.warn(
                            "Timeout while waiting for ScheduledExecutorService of GremlinExecutor to shutdown.");
            } catch (InterruptedException ie) {
                logger.warn(
                        "ScheduledExecutorService on GremlinExecutor may not have shutdown properly as shutdown thread terminated early.");
            }
        }

        try {
            scriptEngines.close();
        } catch (Exception ex) {
            logger.warn("Error while shutting down the ScriptEngines in the GremlinExecutor", ex);
        }

        future.complete(null);
    }, "gremlin-executor-close").start();

    return future;
}

From source file:com.ikanow.aleph2.analytics.storm.utils.StormControllerUtil.java

/**
 * Restarts a storm job by first calling stop, then calling start
 * /*from  w  ww.j  a v  a2  s . co m*/
 * @param bucket
 * @param underlying_artefacts
 * @param yarn_config_dir
 * @param user_lib_paths
 * @param topology
 * @return
 */
public static CompletableFuture<BasicMessageBean> restartJob(final IStormController storm_controller,
        final DataBucketBean bucket, final Optional<String> sub_job,
        final Collection<Object> underlying_artefacts, final Collection<String> user_lib_paths,
        final StormTopology topology, final Map<String, String> config, final String cached_jar_dir) {
    CompletableFuture<BasicMessageBean> stop_future = stopJob(storm_controller, bucket, sub_job);
    try {
        stop_future.get(5, TimeUnit.SECONDS);
        waitForJobToDie(storm_controller, bucket, sub_job, 30L);
    } catch (Exception e) {
        CompletableFuture<BasicMessageBean> error_future = new CompletableFuture<BasicMessageBean>();
        error_future.complete(ErrorUtils.buildErrorMessage(StormControllerUtil.class, "restartJob",
                ErrorUtils.getLongForm("Error stopping storm job: {0}", e)));
        return error_future;
    }
    return startJob(storm_controller, bucket, sub_job, underlying_artefacts, user_lib_paths, topology, config,
            cached_jar_dir);
}

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

@Override
public CompletableFuture<Void> allowReceiveNativeTypes(String... nativeTypes) {
    CompletableFuture<Void> future = new CompletableFuture<>();
    if (!checkOpenAndNoErrors(future)) {
        return future;
    }//from w w w.j ava 2  s . c  om
    send(new SetFeatureMessage().setAllowedNativeTypes(nativeTypes), new ConfirmationResponseHandler(future,
            MessageType.SetFeatureCompleteMessage, "waiting for a server settings complete message"));
    return future;
}

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

public CompletableFuture<byte[]> getLob(String id, long position) {
    CompletableFuture<byte[]> future = new CompletableFuture<>();
    if (!checkOpenAndNoErrors(future)) {
        return future;
    }/*from  w  w w  .  j a v a 2s. co m*/
    send(new LobRequestMessage(id, position, _config.getLobBufferSize()), new ResponseHandler<>(future, m -> {
        if (m.isA(MessageType.ReadyMessage)) {
            return false; // just ignore them
        } else if (m.isA(MessageType.LobAnnouncementMessage)) {
            _messageHandler.setLobConsumer(future);
            return true;
        }
        throw new UnexpectedMessageException("waiting for information response", m);
    }));
    return future;
}

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

@Override
public CompletableFuture<Void> runOnAkkaJoin(Runnable task) {
    synchronized (_joined_akka_cluster) {
        if (_joined_akka_cluster.isDone()) {
            return CompletableFuture.runAsync(task);
        } else {/*from   w  w w . j a v a2s.co  m*/
            final CompletableFuture<Void> on_complete = new CompletableFuture<>();
            _post_join_task_list.add(Tuples._2T(on_complete, task));
            return on_complete;
        }
    }
}

From source file:org.apache.hadoop.hbase.client.AsyncNonMetaRegionLocator.java

private CompletableFuture<HRegionLocation> getRegionLocationInternal(TableName tableName, byte[] row,
        RegionLocateType locateType) {/* www  .ja v a2 s  . c om*/
    // AFTER should be convert to CURRENT before calling this method
    assert !locateType.equals(RegionLocateType.AFTER);
    TableCache tableCache = getTableCache(tableName);
    HRegionLocation loc = locateInCache(tableCache, tableName, row, locateType);
    if (loc != null) {
        return CompletableFuture.completedFuture(loc);
    }
    CompletableFuture<HRegionLocation> future;
    LocateRequest req;
    boolean sendRequest = false;
    synchronized (tableCache) {
        // check again
        loc = locateInCache(tableCache, tableName, row, locateType);
        if (loc != null) {
            return CompletableFuture.completedFuture(loc);
        }
        req = new LocateRequest(row, locateType);
        future = tableCache.allRequests.get(req);
        if (future == null) {
            future = new CompletableFuture<>();
            tableCache.allRequests.put(req, future);
            if (tableCache.hasQuota(maxConcurrentLocateRequestPerTable) && !tableCache.isPending(req)) {
                tableCache.send(req);
                sendRequest = true;
            }
        }
    }
    if (sendRequest) {
        locateInMeta(tableName, req);
    }
    return future;
}

From source file:com.yahoo.pulsar.broker.namespace.NamespaceService.java

private CompletableFuture<LookupResult> createLookupResult(String candidateBroker) throws Exception {

    CompletableFuture<LookupResult> lookupFuture = new CompletableFuture<>();
    try {// w w w. ja  v  a2  s  .c  om
        checkArgument(StringUtils.isNotBlank(candidateBroker),
                "Lookup broker can't be null " + candidateBroker);
        URI uri = new URI(candidateBroker);
        String path = String.format("%s/%s:%s", SimpleLoadManagerImpl.LOADBALANCE_BROKERS_ROOT, uri.getHost(),
                uri.getPort());
        pulsar.getLocalZkCache().getDataAsync(path, loadReportDeserializer).thenAccept(reportData -> {
            if (reportData.isPresent()) {
                LoadReport report = reportData.get();
                lookupFuture.complete(new LookupResult(report.getWebServiceUrl(), report.getWebServiceUrlTls(),
                        report.getPulsarServiceUrl(), report.getPulsarServieUrlTls()));
            } else {
                lookupFuture.completeExceptionally(new KeeperException.NoNodeException(path));
            }
        }).exceptionally(ex -> {
            lookupFuture.completeExceptionally(ex);
            return null;
        });
    } catch (Exception e) {
        lookupFuture.completeExceptionally(e);
    }
    return lookupFuture;
}

From source file:org.apache.pulsar.broker.namespace.NamespaceService.java

protected CompletableFuture<LookupResult> createLookupResult(String candidateBroker) throws Exception {

    CompletableFuture<LookupResult> lookupFuture = new CompletableFuture<>();
    try {//  www. jav a  2 s. c om
        checkArgument(StringUtils.isNotBlank(candidateBroker),
                "Lookup broker can't be null " + candidateBroker);
        URI uri = new URI(candidateBroker);
        String path = String.format("%s/%s:%s", LoadManager.LOADBALANCE_BROKERS_ROOT, uri.getHost(),
                uri.getPort());
        pulsar.getLocalZkCache().getDataAsync(path, pulsar.getLoadManager().get().getLoadReportDeserializer())
                .thenAccept(reportData -> {
                    if (reportData.isPresent()) {
                        ServiceLookupData lookupData = reportData.get();
                        lookupFuture.complete(new LookupResult(lookupData.getWebServiceUrl(),
                                lookupData.getWebServiceUrlTls(), lookupData.getPulsarServiceUrl(),
                                lookupData.getPulsarServiceUrlTls()));
                    } else {
                        lookupFuture.completeExceptionally(new KeeperException.NoNodeException(path));
                    }
                }).exceptionally(ex -> {
                    lookupFuture.completeExceptionally(ex);
                    return null;
                });
    } catch (Exception e) {
        lookupFuture.completeExceptionally(e);
    }
    return lookupFuture;
}

From source file:io.pravega.controller.store.stream.InMemoryStream.java

@Override
CompletableFuture<Void> updateActiveTx(int epoch, UUID txId, Data<Integer> data) {
    Preconditions.checkNotNull(data);/* w w  w . j av a  2  s. c  o  m*/

    CompletableFuture<Void> result = new CompletableFuture<>();
    synchronized (txnsLock) {
        if (!activeTxns.containsKey(txId.toString())) {
            result.completeExceptionally(StoreException.create(StoreException.Type.DATA_NOT_FOUND,
                    "Stream: " + getName() + " Transaction: " + txId.toString()));
        } else {
            activeTxns.compute(txId.toString(), (x, y) -> new Data<>(data.getData(), y.getVersion() + 1));
            result.complete(null);
        }
    }

    return result;
}