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:io.prestosql.operator.OperatorContext.java

private static void updateMemoryFuture(ListenableFuture<?> memoryPoolFuture,
        AtomicReference<SettableFuture<?>> targetFutureReference) {
    if (!memoryPoolFuture.isDone()) {
        SettableFuture<?> currentMemoryFuture = targetFutureReference.get();
        while (currentMemoryFuture.isDone()) {
            SettableFuture<?> settableFuture = SettableFuture.create();
            // We can't replace one that's not done, because the task may be blocked on that future
            if (targetFutureReference.compareAndSet(currentMemoryFuture, settableFuture)) {
                currentMemoryFuture = settableFuture;
            } else {
                currentMemoryFuture = targetFutureReference.get();
            }//from  www .j  a v a 2 s .c o m
        }

        SettableFuture<?> finalMemoryFuture = currentMemoryFuture;
        // Create a new future, so that this operator can un-block before the pool does, if it's moved to a new pool
        memoryPoolFuture.addListener(() -> finalMemoryFuture.set(null), directExecutor());
    }
}

From source file:com.microsoft.windowsazure.mobileservices.zumoe2etestapp.framework.log.DaylightLogger.java

private static ListenableFuture<HttpURLConnection> execute(final HttpEntityEnclosingRequestBase request) {
    final SettableFuture<HttpURLConnection> result = SettableFuture.create();

    AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
        @Override/* w w  w  .j av a  2  s.c o  m*/
        protected Void doInBackground(Void... params) {

            try {
                result.set(createHttpURLConnection(request));
            } catch (Throwable t) {
                result.setException(t);
            }

            return null;
        }
    };

    execute(task);

    return result;
}

From source file:org.apache.twill.internal.ZKMessages.java

/**
 * Creates a message node in zookeeper. The message node created is a PERSISTENT_SEQUENTIAL node.
 *
 * @param zkClient The ZooKeeper client for interacting with ZooKeeper.
 * @param messagePathPrefix ZooKeeper path prefix for the message node.
 * @param message The {@link Message} object for the content of the message node.
 * @param completion A {@link SettableFuture} to reflect the result of message process completion.
 * @param completionResult Object to set to the result future when the message is processed.
 * @param <V> Type of the completion result.
 *///ww w.  j  av  a  2  s  .  c o m
public static <V> void sendMessage(final ZKClient zkClient, String messagePathPrefix, Message message,
        final SettableFuture<V> completion, final V completionResult) {

    // Creates a message and watch for its deletion for completion.
    Futures.addCallback(
            zkClient.create(messagePathPrefix, MessageCodec.encode(message), CreateMode.PERSISTENT_SEQUENTIAL),
            new FutureCallback<String>() {
                @Override
                public void onSuccess(String path) {
                    Futures.addCallback(ZKOperations.watchDeleted(zkClient, path),
                            new FutureCallback<String>() {
                                @Override
                                public void onSuccess(String result) {
                                    completion.set(completionResult);
                                }

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

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

From source file:org.opendaylight.ocpjava.protocol.impl.core.connection.ConnectionAdapterImpl.java

/**
 * @param resultFuture/*from ww w .  j  av a  2s .  co  m*/
 * @param failureInfo
 * @param errorSeverity
 * @param message
 * @return
 */
private static SettableFuture<Boolean> handleTransportChannelFuture(final ChannelFuture resultFuture) {

    final SettableFuture<Boolean> transportResult = SettableFuture.create();

    resultFuture.addListener(new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {

        @Override
        public void operationComplete(final io.netty.util.concurrent.Future<? super Void> future)
                throws Exception {
            transportResult.set(future.isSuccess());
            if (!future.isSuccess()) {
                transportResult.setException(future.cause());
            }
        }
    });
    return transportResult;
}

From source file:com.spotify.futures.FuturesExtra.java

/**
 * Returns a new {@link ListenableFuture} with the result of the first of futures that
 * successfully completes. If all ListenableFutures in futures fails the returned feature
 * fails as well with the Exception of the last failed future. If futures is an empty
 * list the returned future fails immediately with {@link java.util.NoSuchElementException}
 *
 * @param futures a {@link List} of futures
 * @return a new future with the result of the first completing future.
 * @throws NullPointerException if the {@param futures} is null
 *///from w  w  w.j  a va2s  . co  m
public static <T> ListenableFuture<T> select(final List<? extends ListenableFuture<T>> futures) {
    Preconditions.checkNotNull(futures);
    if (futures.isEmpty()) {
        return Futures.immediateFailedFuture(new NoSuchElementException("List is empty"));
    }
    final int count = futures.size();
    final AtomicInteger failures = new AtomicInteger();

    final SettableFuture<T> promise = SettableFuture.create();
    final FutureCallback<T> cb = new FutureCallback<T>() {
        @Override
        public void onSuccess(final T result) {
            promise.set(result);
        }

        @Override
        public void onFailure(Throwable t) {
            if (failures.incrementAndGet() == count) {
                promise.setException(t);
            }
        }
    };

    for (final ListenableFuture<T> future : futures) {
        Futures.addCallback(future, cb);
    }
    return promise;
}

From source file:io.prestosql.operator.Driver.java

private static ListenableFuture<?> firstFinishedFuture(List<ListenableFuture<?>> futures) {
    if (futures.size() == 1) {
        return futures.get(0);
    }/*from   ww  w  .j av a  2s  . c om*/

    SettableFuture<?> result = SettableFuture.create();

    for (ListenableFuture<?> future : futures) {
        future.addListener(() -> result.set(null), directExecutor());
    }

    return result;
}

From source file:org.opendaylight.openflowjava.protocol.impl.connection.ConnectionAdapterImpl.java

/**
 * @param resultFuture/* w w w . j ava  2  s .  c  o  m*/
 * @param failureInfo
 * @param errorSeverity
 * @param message
 * @return
 */
private static SettableFuture<Boolean> handleTransportChannelFuture(ChannelFuture resultFuture,
        final String failureInfo, final ErrorSeverity errorSeverity, final String message) {

    final SettableFuture<Boolean> transportResult = SettableFuture.create();

    resultFuture.addListener(new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {

        @Override
        public void operationComplete(io.netty.util.concurrent.Future<? super Void> future) throws Exception {
            transportResult.set(future.isSuccess());
            if (!future.isSuccess()) {
                transportResult.setException(future.cause());
            }
        }
    });
    return transportResult;
}

From source file:io.prestosql.execution.scheduler.SqlQueryScheduler.java

private static ListenableFuture<?> whenAllStages(Collection<SqlStageExecution> stages,
        Predicate<StageState> predicate) {
    checkArgument(!stages.isEmpty(), "stages is empty");
    Set<StageId> stageIds = newConcurrentHashSet(
            stages.stream().map(SqlStageExecution::getStageId).collect(toSet()));
    SettableFuture<?> future = SettableFuture.create();

    for (SqlStageExecution stage : stages) {
        stage.addStateChangeListener(state -> {
            if (predicate.test(state) && stageIds.remove(stage.getStageId()) && stageIds.isEmpty()) {
                future.set(null);
            }/*ww w .  jav a2 s  .  com*/
        });
    }

    return future;
}

From source file:com.facebook.buck.remoteexecution.grpc.GrpcRemoteExecutionClients.java

/** Reads a ByteStream onto the arg consumer. */
public static ListenableFuture<Void> readByteStream(String instanceName, Protocol.Digest digest,
        ByteStreamStub byteStreamStub, ThrowingConsumer<ByteString, IOException> dataConsumer) {
    String name = getReadResourceName(instanceName, digest);
    SettableFuture<Void> future = SettableFuture.create();
    byteStreamStub.read(ReadRequest.newBuilder().setResourceName(name).setReadLimit(0).setReadOffset(0).build(),
            new StreamObserver<ReadResponse>() {
                @Override/* w  ww  .  j a va 2  s  .  com*/
                public void onNext(ReadResponse value) {
                    try {
                        dataConsumer.accept(value.getData());
                    } catch (IOException e) {
                        onError(e);
                    }
                }

                @Override
                public void onError(Throwable t) {
                    future.setException(t);
                }

                @Override
                public void onCompleted() {
                    future.set(null);
                }
            });
    return future;
}

From source file:org.glowroot.central.util.Session.java

private static ListenableFuture<ResultSet> throttle(DoUnderThrottle doUnderThrottle, Semaphore overallSemaphore)
        throws Exception {
    overallSemaphore.acquire();/*  w w  w  .j  a  v a 2s  .c o m*/
    SettableFuture<ResultSet> outerFuture = SettableFuture.create();
    ResultSetFuture innerFuture;
    try {
        innerFuture = doUnderThrottle.execute();
    } catch (Throwable t) {
        overallSemaphore.release();
        throw t;
    }
    Futures.addCallback(innerFuture, new FutureCallback<ResultSet>() {
        @Override
        public void onSuccess(ResultSet result) {
            overallSemaphore.release();
            outerFuture.set(result);
        }

        @Override
        public void onFailure(Throwable t) {
            overallSemaphore.release();
            outerFuture.setException(t);
        }
    }, MoreExecutors.directExecutor());
    return outerFuture;
}