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

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

Introduction

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

Prototype

public static <V> SettableFuture<V> create() 

Source Link

Document

Creates a new SettableFuture that can be completed or cancelled by a later method call.

Usage

From source file:io.crate.operation.join.SinglePagePageableTaskIterable.java

@Override
public ListenableFuture<Void> fetchPage(PageInfo pageInfo) throws NoSuchElementException {
    this.pageInfo(pageInfo);

    final SettableFuture<Void> future = SettableFuture.create();
    Futures.addCallback(currentTaskResult.fetch(pageInfo), new FutureCallback<PageableTaskResult>() {
        @Override//ww w  .  j a  va 2 s . c om
        public void onSuccess(@Nullable PageableTaskResult result) {
            if (result == null) {
                future.setException(new IllegalArgumentException("PageableTaskResult is null"));
            }
            currentTaskResult = result;
            future.set(null);
        }

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

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

protected AbstractChainedTask() {
    this.result = SettableFuture.create();
    this.resultList = ImmutableList.<ListenableFuture<TaskResult>>of(this.result);
}

From source file:com.navercorp.nbasearc.gcp.Gateway.java

ListenableFuture<?> init(SingleThreadEventLoopTrunk eventLoopTrunk, int reconnectInterval) {
    final SettableFuture<?> sf = SettableFuture.create();

    for (int i = 0; i < concnt; i++) {
        cons[i] = PhysicalConnection.create(ip, port, eventLoopTrunk.roundrobinEventLoop(), this,
                reconnectInterval);/*w  w  w .j ava2 s.  c om*/

        final ListenableFuture<?> conFuture = cons[i].connect();
        conFuture.addListener(new Runnable() {
            @Override
            public void run() {
                try {
                    conFuture.get();
                    sf.set(null);
                } catch (InterruptedException e) {
                    log.error("Exception occured while connecting to {}", Gateway.this, e);
                } catch (ExecutionException e) {
                    log.error("Exception occured while connecting to {}", Gateway.this, e);
                }
            }
        }, MoreExecutors.directExecutor());
    }

    return sf;
}

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

protected AsyncChainedTask() {
    result = SettableFuture.create();
    ListenableFuture<TaskResult> resultFallback = Futures.withFallback(result,
            new FutureFallback<TaskResult>() {
                @Override//from  ww w.j ava2s . c  o m
                public ListenableFuture<TaskResult> create(@Nonnull Throwable t) throws Exception {
                    return Futures.immediateFuture((TaskResult) RowCountResult.error(t));
                }
            });
    resultList = new ArrayList<>();
    resultList.add(resultFallback);
}

From source file:com.continuuity.weave.common.Services.java

/**
 * Performs the actual logic of chain Service start/stop.
 *//*from  w  w w .j  av a 2  s .c o m*/
private static ListenableFuture<List<ListenableFuture<Service.State>>> doChain(boolean doStart,
        Service firstService, Service... moreServices) {
    SettableFuture<List<ListenableFuture<Service.State>>> resultFuture = SettableFuture.create();
    List<ListenableFuture<Service.State>> result = Lists.newArrayListWithCapacity(moreServices.length + 1);

    ListenableFuture<Service.State> future = doStart ? firstService.start() : firstService.stop();
    future.addListener(
            createChainListener(future, moreServices, new AtomicInteger(0), result, resultFuture, doStart),
            Threads.SAME_THREAD_EXECUTOR);
    return resultFuture;
}

From source file:org.opendaylight.mdsal.dom.broker.TransactionChainReadTransaction.java

@Override
public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final LogicalDatastoreType store,
        final YangInstanceIdentifier path) {
    final SettableFuture<Optional<NormalizedNode<?, ?>>> readResult = SettableFuture.create();

    Futures.addCallback(previousWriteTxFuture, new FutureCallback<Void>() {
        @Override//from w ww .j  a va  2  s .  c o m
        public void onSuccess(@Nullable final Void result) {
            Futures.addCallback(delegateReadTx.read(store, path),
                    new FutureCallback<Optional<NormalizedNode<?, ?>>>() {

                        @Override
                        public void onSuccess(@Nullable final Optional<NormalizedNode<?, ?>> result) {
                            readResult.set(result);
                        }

                        @Override
                        public void onFailure(final Throwable throwable) {
                            txChain.transactionFailed(TransactionChainReadTransaction.this, throwable);
                            readResult.setException(throwable);
                        }
                    });
        }

        @Override
        public void onFailure(final Throwable throwable) {
            // we don't have to notify txchain about this failure
            // failed write transaction should do this
            readResult.setException(throwable);
        }
    });

    return Futures.makeChecked(readResult, ReadFailedException.MAPPER);
}

From source file:io.viewserver.client.ClientSubscription.java

public Future<List<Map<String, Object>>> getSnapshot() {
    SettableFuture<List<Map<String, Object>>> future = SettableFuture.create();
    deserialiserOperator.addEventHandler(new DeserialiserEventHandlerBase() {
        @Override//from w ww . j  a v  a  2s.c o m
        public void onSubscriptionError(DeserialiserOperator deserialiserOperator, String msg) {
            future.setException(new ViewServerClientException(msg));
        }

        @Override
        public void onSnapshotComplete(DeserialiserOperator deserialiserOperator) {
            ArrayList<Map<String, Object>> snapshot = new ArrayList<>();
            Schema schema = deserialiserOperator.getOutput().getSchema();
            IRowSequence allRows = deserialiserOperator.getOutput().getAllRows();
            List<ColumnHolder> columnHolders = schema.getColumnHolders();
            int count = columnHolders.size();
            while (allRows.moveNext()) {
                HashMap<String, Object> row = new HashMap<>();
                for (int i = 0; i < count; i++) {
                    ColumnHolder columnHolder = columnHolders.get(i);
                    if (columnHolder == null) {
                        continue;
                    }
                    row.put(columnHolder.getName(),
                            ColumnHolderUtils.getValue(columnHolder, allRows.getRowId()));
                }
                snapshot.add(row);
            }
            future.set(snapshot);
        }
    });
    return future;
}

From source file:com.facebook.presto.execution.buffer.OutputBufferMemoryManager.java

public OutputBufferMemoryManager(long maxBufferedBytes, SystemMemoryUsageListener systemMemoryUsageListener,
        Executor notificationExecutor) {
    checkArgument(maxBufferedBytes > 0, "maxBufferedBytes must be > 0");
    this.maxBufferedBytes = maxBufferedBytes;
    this.systemMemoryUsageListener = requireNonNull(systemMemoryUsageListener,
            "systemMemoryUsageListener is null");
    this.notificationExecutor = requireNonNull(notificationExecutor, "notificationExecutor is null");

    notFull = SettableFuture.create();
    notFull.set(null);/*from w  ww.  j  ava 2 s.c  o  m*/
}

From source file:org.opendaylight.openflowjava.protocol.impl.core.TcpConnectionInitializer.java

@Override
public ListenableFuture<Boolean> shutdown() {
    final SettableFuture<Boolean> result = SettableFuture.create();
    workerGroup.shutdownGracefully();// ww  w  . ja v  a 2 s. co m
    return result;
}

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

/**
 * Returns a future that fails with a {@link TimeoutException} if the parent future has not
 * finished before the timeout. The new returned future will always be executed on the provided
 * scheduledExecutorService, even when the parent future does not timeout.
 *
 * @param scheduledExecutorService executor that runs the timeout code. If the future times out,
 *                                 this is also the thread any callbacks will run on.
 * @param future                   the future to wrap as a timeout future.
 * @param timeout                  how long to wait before timing out a future
 * @param unit                     unit of the timeout
 * @return a future that may timeout before the parent future is done.
 */// www  .j a v a 2s  .  com
public static <T> ListenableFuture<T> makeTimeoutFuture(ScheduledExecutorService scheduledExecutorService,
        ListenableFuture<T> future, final long timeout, final TimeUnit unit) {
    final SettableFuture<T> promise = SettableFuture.create();

    scheduledExecutorService.schedule(new Runnable() {
        @Override
        public void run() {
            String message = "Future timed out after " + timeout + " " + unit.name();
            promise.setException(new TimeoutException(message));
        }
    }, timeout, unit);

    Futures.addCallback(future, new FutureCallback<T>() {
        @Override
        public void onSuccess(T result) {
            promise.set(result);
        }

        @Override
        public void onFailure(Throwable t) {
            promise.setException(t);
        }
    }, scheduledExecutorService);

    return promise;
}