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.robotninjas.barge.state.ReplicaManager.java

private ListenableFuture<AppendEntriesResponse> sendUpdate() {

    running++;/*ww  w .  ja v a  2s  .c o m*/
    requested = false;

    // if the last rpc call was successful then try to send
    // as many updates as we can, otherwise, if we're
    // probing backwards, only send one entry as a probe, as
    // soon as we have a successful call forwards will become
    // true and we can catch up quickly
    GetEntriesResult result = log.getEntriesFrom(nextIndex, forwards ? BATCH_SIZE : 1);

    final AppendEntries request = AppendEntries.newBuilder().setTerm(log.currentTerm())
            .setLeaderId(log.self().toString()).setPrevLogIndex(result.lastLogIndex())
            .setPrevLogTerm(result.lastLogTerm()).setCommitIndex(log.commitIndex())
            .addAllEntries(result.entries()).build();

    LOGGER.debug("Sending update to {} prevLogIndex {} prevLogTerm {}", remote, result.lastLogIndex(),
            result.lastLogTerm());
    final ListenableFuture<AppendEntriesResponse> response = client.appendEntries(remote, request);

    final SettableFuture<AppendEntriesResponse> previousResponse = nextResponse;

    Futures.addCallback(response, new FutureCallback<AppendEntriesResponse>() {

        @Override
        public void onSuccess(@Nullable AppendEntriesResponse result) {
            running--;
            updateNextIndex(request, result);
            if (result.getSuccess()) {
                previousResponse.set(result);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            running--;
            requested = false;
            previousResponse.setException(t);
        }

    });

    nextResponse = SettableFuture.create();

    return response;

}

From source file:com.griddynamics.jagger.master.AbstractDistributor.java

@Override
public Service distribute(final ExecutorService executor, final String sessionId, final String taskId,
        final Multimap<NodeType, NodeId> availableNodes, final Coordinator coordinator, final T task,
        final DistributionListener listener) {
    Set<Qualifier<?>> qualifiers = getQualifiers();

    final Map<NodeId, RemoteExecutor> remotes = Maps.newHashMap();

    for (NodeId nodeId : availableNodes.get(NodeType.KERNEL)) {

        boolean canRunTheCommand = coordinator.canExecuteCommands(nodeId, qualifiers);

        if (canRunTheCommand) {
            remotes.put(nodeId, coordinator.getExecutor(nodeId));
        } else {/* ww  w  . j a v a  2  s  .  c o m*/
            log.debug("command type {} are not supported by kernel {}", qualifiers, nodeId);
        }
    }

    if (remotes.isEmpty()) {
        throw new NodeNotFound("Nodes not found to distribute the task");
    }

    final Service service = performDistribution(executor, sessionId, taskId, task, remotes, availableNodes,
            coordinator);
    return new ForwardingService() {

        @Override
        public ListenableFuture<State> start() {

            ListenableFuture<Nothing> runListener = Futures
                    .makeListenable(executor.submit(new Callable<Nothing>() {
                        @Override
                        public Nothing call() {
                            listener.onDistributionStarted(sessionId, taskId, task, remotes.keySet());
                            return Nothing.INSTANCE;
                        }
                    }));

            return Futures.chain(runListener, new Function<Nothing, ListenableFuture<State>>() {
                @Override
                public ListenableFuture<State> apply(Nothing input) {
                    return doStart();
                }
            });
        }

        private ListenableFuture<State> doStart() {
            return super.start();
        }

        @Override
        protected Service delegate() {
            return service;
        }

        @Override
        public ListenableFuture<State> stop() {
            ListenableFuture<State> stop = super.stop();

            return Futures.chain(stop, new Function<State, ListenableFuture<State>>() {
                @Override
                public ListenableFuture<State> apply(final State input) {

                    final SettableFuture<State> result = SettableFuture.create();
                    executor.execute(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                listener.onTaskDistributionCompleted(sessionId, taskId, task);
                            } finally {
                                result.set(input);
                            }
                        }
                    });
                    return result;
                }
            });
        }

    };
}

From source file:com.google.devtools.build.lib.remote.ByteStreamUploader.java

private void startAsyncUploadWithRetry(Chunker chunker, Retrier.Backoff backoffTimes,
        SettableFuture<Void> overallUploadResult) {

    AsyncUpload.Listener listener = new AsyncUpload.Listener() {
        @Override/*from  w  w w  . jav a2s  . c om*/
        public void success() {
            overallUploadResult.set(null);
        }

        @Override
        public void failure(Status status) {
            StatusException cause = status.asException();
            long nextDelayMillis = backoffTimes.nextDelayMillis();
            if (nextDelayMillis < 0 || !retrier.isRetriable(status)) {
                // Out of retries or status not retriable.
                RetryException error = new RetryException(cause, backoffTimes.getRetryAttempts());
                overallUploadResult.setException(error);
            } else {
                retryAsyncUpload(nextDelayMillis, chunker, backoffTimes, overallUploadResult);
            }
        }

        private void retryAsyncUpload(long nextDelayMillis, Chunker chunker, Retrier.Backoff backoffTimes,
                SettableFuture<Void> overallUploadResult) {
            try {
                ListenableScheduledFuture<?> schedulingResult = retryService.schedule(
                        Context.current().wrap(
                                () -> startAsyncUploadWithRetry(chunker, backoffTimes, overallUploadResult)),
                        nextDelayMillis, MILLISECONDS);
                // In case the scheduled execution errors, we need to notify the overallUploadResult.
                schedulingResult.addListener(() -> {
                    try {
                        schedulingResult.get();
                    } catch (Exception e) {
                        overallUploadResult
                                .setException(new RetryException(e, backoffTimes.getRetryAttempts()));
                    }
                }, MoreExecutors.directExecutor());
            } catch (RejectedExecutionException e) {
                // May be thrown by .schedule(...) if i.e. the executor is shutdown.
                overallUploadResult.setException(new RetryException(e, backoffTimes.getRetryAttempts()));
            }
        }
    };

    try {
        chunker.reset();
    } catch (IOException e) {
        overallUploadResult.setException(e);
        return;
    }

    AsyncUpload newUpload = new AsyncUpload(channel, callCredentials, callTimeoutSecs, instanceName, chunker,
            listener);
    overallUploadResult.addListener(() -> {
        if (overallUploadResult.isCancelled()) {
            newUpload.cancel();
        }
    }, MoreExecutors.directExecutor());
    newUpload.start();
}

From source file:io.v.v23.syncbase.Batch.java

@CheckReturnValue
private static ListenableFuture<Boolean> tryBatch(final VContext ctx, final Database db,
        final BatchOptions opts, final BatchOperation op) {
    final SettableFuture<Boolean> ret = SettableFuture.create();
    Futures.addCallback(db.beginBatch(ctx, opts), new FutureCallback<BatchDatabase>() {
        @Override/*from   ww  w  . java2 s. c  om*/
        public void onFailure(Throwable t) {
            ret.setException(t);
        }

        @Override
        public void onSuccess(final BatchDatabase batch) {
            Futures.addCallback(op.run(batch), new FutureCallback<Void>() {
                @Override
                public void onFailure(final Throwable t) {
                    Futures.addCallback(batch.abort(ctx), new FutureCallback<Void>() {
                        @Override
                        public void onSuccess(Void result) {
                            ret.setException(t);
                        }

                        @Override
                        public void onFailure(Throwable newT) {
                            ret.setException(t);
                        }
                    });
                }

                @Override
                public void onSuccess(Void result) {
                    Futures.addCallback(opts.getReadOnly() ? batch.abort(ctx) : batch.commit(ctx),
                            new FutureCallback<Void>() {
                                @Override
                                public void onSuccess(Void result) {
                                    ret.set(true); // success
                                }

                                @Override
                                public void onFailure(Throwable t) {
                                    if (t instanceof ConcurrentBatchException) {
                                        // retry
                                        ret.set(false);
                                    } else {
                                        ret.setException(t);
                                    }
                                }
                            });
                }
            });
        }
    });
    return ret;
}

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

protected ListenableFuture<Boolean> createNode(String path, byte[] data, boolean isEphemeral) {
    final SettableFuture<Boolean> result = SettableFuture.create();

    try {/*  w w  w . j  a  v  a2  s . com*/
        client.create().withMode(isEphemeral ? CreateMode.EPHEMERAL : CreateMode.PERSISTENT).forPath(path,
                data);
        LOG.info("Created 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 createNode:", e));
    }
    return result;
}

From source file:com.github.fhuss.storm.cassandra.executor.AsyncExecutor.java

/**
 * Asynchronously executes the specified batch statement. Inputs will be passed to
 * the {@link #handler} once query succeed or failed.
 *//*from w w w  . j  a  va 2  s .c  o m*/
public SettableFuture<T> execAsync(final Statement statement, final T inputs, AsyncResultHandler<T> handler) {
    final SettableFuture<T> settableFuture = SettableFuture.create();
    pending.put(settableFuture, true);
    ResultSetFuture future = session.executeAsync(statement);
    Futures.addCallback(future, new FutureCallback<ResultSet>() {
        public void release() {
            pending.remove(settableFuture);
        }

        @Override
        public void onSuccess(ResultSet result) {
            release();
            settableFuture.set(inputs);
            handler.success(inputs);
        }

        @Override
        public void onFailure(Throwable t) {
            LOG.error(String.format("Failed to execute statement '%s' ", statement), t);
            release();
            settableFuture.setException(t);
            handler.failure(t, inputs);
        }
    }, executorService);
    return settableFuture;
}

From source file:io.crate.executor.transport.distributed.DownstreamOperationContext.java

public DownstreamOperationContext(DownstreamOperation downstreamOperation,
        final SettableFuture<Object[][]> listener, Streamer<?>[] streamers,
        DistributedRequestContextManager.DoneCallback doneCallback) {
    this.mergeOperationsLeft = new AtomicInteger(downstreamOperation.numUpstreams());
    this.downstreamOperation = downstreamOperation;
    this.listener = listener;
    Futures.addCallback(downstreamOperation.result(), new FutureCallback<Object[][]>() {
        @Override//  ww w .  j a  v a 2s  .  com
        public void onSuccess(@Nullable Object[][] result) {
            listener.set(result);
        }

        @Override
        public void onFailure(Throwable t) {
            listener.setException(t);

        }
    });
    this.streamers = streamers;
    this.doneCallback = doneCallback;
}

From source file:org.opendaylight.centinel.impl.dashboard.CentinelDashboardImpl.java

@Override
public Future<RpcResult<DashboardIncrementTestOutput>> dashboardIncrementTest(
        DashboardIncrementTestInput input) {

    final SettableFuture<RpcResult<DashboardIncrementTestOutput>> futureResult = SettableFuture.create();

    futureResult.set(RpcResultBuilder.<DashboardIncrementTestOutput>success(
            new DashboardIncrementTestOutputBuilder().setMessage("SUCCESS").build()).build());
    /**/* w w w  . j ava2  s.  c  om*/
     * code to increase the counter for streamID:Start
     */
    StreamCounterInfoCache streamCounterInfoCache = StreamCounterInfoCache.getInstance();
    streamCounterInfoCache.incrementCounter(input.getStreamID());
    /**
     * code to increase the counter for streamID:End
     */
    return futureResult;
}

From source file:c5db.C5DB.java

@Override
public ListenableFuture<ImmutableMap<ModuleType, Integer>> getOnlineModules() {
    final SettableFuture<ImmutableMap<ModuleType, Integer>> future = SettableFuture.create();
    serverFiber.execute(() -> future.set(ImmutableMap.copyOf(onlineModuleToPortMap)));
    return future;
}

From source file:c5db.C5DB.java

@Override
public ImmutableMap<ModuleType, C5Module> getModules()
        throws ExecutionException, InterruptedException, TimeoutException {
    final SettableFuture<ImmutableMap<ModuleType, C5Module>> future = SettableFuture.create();
    serverFiber.execute(() -> future.set(ImmutableMap.copyOf(allModules)));
    return future.get(1, TimeUnit.SECONDS);
}