Example usage for com.google.common.util.concurrent SettableFuture set

List of usage examples for com.google.common.util.concurrent SettableFuture set

Introduction

In this page you can find the example usage for com.google.common.util.concurrent SettableFuture set.

Prototype

@Override
    public boolean set(@Nullable V value) 

Source Link

Usage

From source file:org.opendaylight.ofconfig.southbound.impl.api.ver12.helper.AbstractOfconfigVer12HandlerHelper.java

private Future<RpcResult<Void>> buildNotFoundResult(String nodeId) {

    SettableFuture<RpcResult<Void>> resultFuture = SettableFuture.create();

    RpcResult<Void> rpcResult = RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION,
            "No corresponding nodes are found in the topology,nodeId:" + nodeId).build();

    resultFuture.set(rpcResult);
    return resultFuture;

}

From source file:com.android.builder.internal.aapt.AbstractProcessExecutionAapt.java

@Override
@NonNull/*from  w w w.  j a v a2 s  . c o m*/
protected ListenableFuture<Void> makeValidatedPackage(@NonNull AaptPackageConfig config) throws AaptException {
    ProcessInfoBuilder builder = makePackageProcessBuilder(config);

    final ProcessInfo processInfo = builder.createProcess();
    ListenableFuture<ProcessResult> execResult = mProcessExecutor.submit(processInfo, mProcessOutputHandler);

    final SettableFuture<Void> result = SettableFuture.create();
    Futures.addCallback(execResult, new FutureCallback<ProcessResult>() {
        @Override
        public void onSuccess(ProcessResult processResult) {
            try {
                processResult.rethrowFailure().assertNormalExitValue();
                result.set(null);
            } catch (Exception e) {
                result.setException(e);
            }
        }

        @Override
        public void onFailure(@NonNull Throwable t) {
            result.setException(t);
        }
    });

    return result;
}

From source file:io.prestosql.execution.scheduler.group.DynamicLifespanScheduler.java

@Override
public void onLifespanFinished(Iterable<Lifespan> newlyCompletedDriverGroups) {
    checkState(initialScheduled);/*from w  w w  . j  a v  a 2  s. c o m*/

    SettableFuture<?> newDriverGroupReady;
    synchronized (this) {
        for (Lifespan newlyCompletedDriverGroup : newlyCompletedDriverGroups) {
            checkArgument(!newlyCompletedDriverGroup.isTaskWide());
            recentlyCompletedDriverGroups.add(newlyCompletedDriverGroup);
        }
        newDriverGroupReady = this.newDriverGroupReady;
    }
    newDriverGroupReady.set(null);
}

From source file:io.crate.executor.transport.task.UpsertByIdTask.java

private void executeUpsertRequest(final UpsertById.Item item, final SettableFuture<Long> future) {
    final FutureCallback<Long> callback = new FutureCallback<Long>() {
        @Override/*w  w w. j  a  va  2  s .  c o  m*/
        public void onSuccess(@Nullable Long result) {
            future.set(result);
        }

        @Override
        public void onFailure(@Nonnull Throwable t) {
            future.setException(t);
        }
    };
    ListenableFuture<Long> f = executeUpsertRequest(item);
    Futures.addCallback(f, callback);
}

From source file:io.prestosql.execution.scheduler.group.FixedLifespanScheduler.java

public void onLifespanFinished(Iterable<Lifespan> newlyCompletedDriverGroups) {
    checkState(initialScheduled);/*from   w w w  . java2s  .  com*/

    SettableFuture<?> newDriverGroupReady;
    synchronized (this) {
        for (Lifespan newlyCompletedDriverGroup : newlyCompletedDriverGroups) {
            checkArgument(!newlyCompletedDriverGroup.isTaskWide());
            recentlyCompletedDriverGroups.add(newlyCompletedDriverGroup);
        }
        newDriverGroupReady = this.newDriverGroupReady;
    }
    newDriverGroupReady.set(null);
}

From source file:io.crate.executor.transport.task.elasticsearch.QueryThenFetchPageableTaskResult.java

/**
 *
 * @param pageInfo identifying the page to fetch
 * @return a future for a new task result containing the requested page.
 *///from   w ww.j  ava  2  s  .c  o  m
@Override
public ListenableFuture<PageableTaskResult> fetch(final PageInfo pageInfo) {
    final long pageSourceBeginning = currentPageInfo.position() - startIndexAtPageSource;
    if (pageInfo.position() < pageSourceBeginning) {
        logger.trace("paging backwards for page {}. issue new QTF query", pageInfo);
        // backward paging - not optimized
        return fetchWithNewQTF(pageInfo);
    }
    final long pageSourceEnd = currentPageInfo.position() + (pageSource.size() - startIndexAtPageSource);
    final long gap = Math.max(0, pageInfo.position() - pageSourceEnd);

    final long restSize;
    if (gap == 0) {
        restSize = pageSourceEnd - pageInfo.position();
    } else {
        restSize = 0;
    }

    final SettableFuture<PageableTaskResult> future = SettableFuture.create();
    if (restSize >= pageInfo.size()) {
        // don't need to fetch nuttin'
        logger.trace("can satisfy page {} with current page source", pageInfo);
        future.set(new QueryThenFetchPageableTaskResult(operation, ctx, extractors, pageInfo, pageSource,
                startIndexAtPageSource + (pageInfo.position() - currentPageInfo.position())));
    } else if (restSize <= 0) {
        if (gap + pageInfo.size() > MAX_GAP_PAGESIZE) {
            // if we have to fetch more than default pagesize, issue another query
            logger.trace("issue a new QTF query for page {}. gap is too big.", pageInfo);
            return fetchWithNewQTF(pageInfo);
        } else {
            logger.trace("fetch another page: {}, we only got a small gap.", pageInfo);
            fetchFromSource((int) (pageInfo.position() - gap), (int) (pageInfo.size() + gap),
                    new FutureCallback<ObjectArray<Object[]>>() {
                        @Override
                        public void onSuccess(@Nullable ObjectArray<Object[]> result) {
                            future.set(new QueryThenFetchPageableTaskResult(operation, ctx, extractors,
                                    pageInfo, result, Math.min(result.size(), gap)));
                        }

                        @Override
                        public void onFailure(Throwable t) {
                            closeSafe();
                            future.setException(t);
                        }
                    });
        }
    } else if (restSize > 0) {
        logger.trace("we got {} docs left for page {}. need to fetch {}", restSize, pageInfo,
                pageInfo.size() - restSize);
        // we got a rest, need to combine stuff
        fetchFromSource(pageInfo.position(), (int) (pageInfo.size() - restSize),
                new FutureCallback<ObjectArray<Object[]>>() {
                    @Override
                    public void onSuccess(@Nullable ObjectArray<Object[]> result) {

                        MultiObjectArrayBigArray<Object[]> merged = new MultiObjectArrayBigArray<>(0,
                                pageSource.size() + result.size(), pageSource, result);
                        future.set(new QueryThenFetchPageableTaskResult(operation, ctx, extractors, pageInfo,
                                merged,
                                startIndexAtPageSource + (pageInfo.position() - currentPageInfo.position())));
                    }

                    @Override
                    public void onFailure(Throwable t) {
                        closeSafe();
                        future.setException(t);
                    }
                });
    }
    return future;
}

From source file:com.vmware.photon.controller.common.zookeeper.LeaderElectedServiceNode.java

@Override
protected synchronized ListenableFuture<Void> joinCondition() {
    logger.debug("Creating the leader latch for {}", serviceName);
    leaderLatch = new LeaderLatch(zkClient, "/elections/" + serviceName, address.toString());

    try {/*from  w  w w  . ja v  a 2s .co m*/
        leaderLatch.start();
    } catch (Exception e) {
        return Futures.immediateFailedFuture(e);
    }

    final SettableFuture<Void> promise = SettableFuture.create();
    waitDone = new CountDownLatch(1);

    leaderWait = executorService.submit(new Runnable() {
        @Override
        public void run() {
            try {
                leaderLatch.await();
                logger.debug("{} is a leader now", serviceName);
                promise.set(VOID);
            } catch (InterruptedException e) {
                logger.debug("Leader latch waiting for {} interrupted", serviceName);

                waitDone.countDown(); // See comment below to understand why we do that both in 'finally' and here

                promise.setException(new InterruptedException("Interrupted while waiting for leader election"));
                Thread.currentThread().interrupt();

            } catch (Exception e) {
                promise.setException(e);
            } finally {
                // There is an interesting race condition here:
                // 1. Leader elected service starts up and it's not a leader, so it blocks on leader latch acquisition;
                // 2. ZK goes away, acquisition gets interrupted;
                // 3. failure callback for the acquisition gets fired and (currently) runs System.exit(0);
                // 4. According to the Java language spec 'finally' block is NOT guaranteed to run when JVM is exiting BUT
                //    we have a shutdown hook that attempts to leave the service and triggers 'cleanup' method below, where
                //    it blocks indefinitely on waiting for 'waitDone' countdown latch IF 'finally' doesn't execute.
                //
                // TODO(olegs): maybe find a cleaner way orchestrate the shutdown?
                waitDone.countDown();
            }
        }
    });

    return promise;
}

From source file:org.apache.hadoop.hive.ql.exec.tez.TezSessionPool.java

private ListenableFuture<Boolean> createDummyFuture() {
    SettableFuture<Boolean> f = SettableFuture.create();
    f.set(true);
    return f;
}

From source file:com.groupon.mesos.zookeeper.ZookeeperMasterDetector.java

@Subscribe
public void processDetect(final DetectMessage message) {
    final SettableFuture<MasterInfo> future = message.getFuture();
    final MasterInfo previous = message.getPrevious();
    final MasterInfo currentLeader = getMaster();

    if (!Objects.equal(currentLeader, previous)) {
        LOG.debug("Master has changed: %s -> %s", previous, currentLeader);
        future.set(currentLeader);
    } else {/*from  w  ww . j  a va 2  s . com*/
        LOG.debug("Master unchanged, queueing");
        futures.add(message);
    }
}

From source file:com.twitter.heron.statemgr.zookeeper.curator.CuratorStateManager.java

protected ListenableFuture<Boolean> deleteNode(String path) {
    final SettableFuture<Boolean> result = SettableFuture.create();

    try {//from   w  ww  . jav a 2s .c om
        client.delete().withVersion(-1).forPath(path);
        LOG.info("Deleted node for path: " + path);
        result.set(true);

        // Suppress it since forPath() throws Exception
        // SUPPRESS CHECKSTYLE IllegalCatch
    } catch (Exception e) {
        result.setException(new RuntimeException("Could not deleteNode", e));
    }

    return result;
}