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

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

Introduction

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

Prototype

@Override
    public void addListener(Runnable runnable, Executor executor) 

Source Link

Usage

From source file:com.continuuity.weave.zookeeper.ZKOperations.java

/**
 * Watch for data changes of the given path. The callback will be triggered whenever changes has been
 * detected. Note that the callback won't see every single changes, as that's not the guarantee of ZooKeeper.
 * If the node doesn't exists, it will watch for its creation then starts watching for data changes.
 * When the node is deleted afterwards,//from www  .  j av  a  2  s. com
 *
 * @param zkClient The {@link ZKClient} for the operation
 * @param path Path to watch
 * @param callback Callback to be invoked when data changes is detected.
 * @return A {@link Cancellable} to cancel the watch.
 */
public static Cancellable watchData(final ZKClient zkClient, final String path, final DataCallback callback) {
    final AtomicBoolean cancelled = new AtomicBoolean(false);
    Futures.addCallback(zkClient.getData(path, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (!cancelled.get()) {
                watchData(zkClient, path, callback);
            }
        }
    }), new FutureCallback<NodeData>() {
        @Override
        public void onSuccess(NodeData result) {
            if (!cancelled.get()) {
                callback.updated(result);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            if (t instanceof KeeperException && ((KeeperException) t).code() == KeeperException.Code.NONODE) {
                final SettableFuture<String> existCompletion = SettableFuture.create();
                existCompletion.addListener(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            if (!cancelled.get()) {
                                watchData(zkClient, existCompletion.get(), callback);
                            }
                        } catch (Exception e) {
                            LOG.error("Failed to watch data for path " + path, e);
                        }
                    }
                }, Threads.SAME_THREAD_EXECUTOR);
                watchExists(zkClient, path, existCompletion);
                return;
            }
            LOG.error("Failed to watch data for path " + path + " " + t, t);
        }
    });
    return new Cancellable() {
        @Override
        public void cancel() {
            cancelled.set(true);
        }
    };
}

From source file:org.apache.twill.zookeeper.ZKOperations.java

private static <T> void watchChanges(final Operation<T> operation, final String path,
        final Callback<T> callback, final AtomicBoolean cancelled) {
    Futures.addCallback(operation.exec(path, new Watcher() {
        @Override/*from w  w  w  .ja  va 2 s  .  c o m*/
        public void process(WatchedEvent event) {
            if (!cancelled.get()) {
                watchChanges(operation, path, callback, cancelled);
            }
        }
    }), new FutureCallback<T>() {
        @Override
        public void onSuccess(T result) {
            if (!cancelled.get()) {
                callback.updated(result);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            if (t instanceof KeeperException && ((KeeperException) t).code() == KeeperException.Code.NONODE) {
                final SettableFuture<String> existCompletion = SettableFuture.create();
                existCompletion.addListener(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            if (!cancelled.get()) {
                                watchChanges(operation, existCompletion.get(), callback, cancelled);
                            }
                        } catch (Exception e) {
                            LOG.error("Failed to watch children for path " + path, e);
                        }
                    }
                }, Threads.SAME_THREAD_EXECUTOR);
                watchExists(operation.getZKClient(), path, existCompletion);
                return;
            }
            LOG.error("Failed to watch data for path " + path + " " + t, t);
        }
    });
}

From source file:com.proofpoint.concurrent.BenchmarkWhenAnyCompleteCancelOthers.java

@Benchmark
public void benchmark() throws Exception {
    Semaphore semaphore = new Semaphore(futureCount);

    ArrayList<SettableFuture<?>> futures = new ArrayList<>();
    for (int i = 0; i < futureCount; i++) {
        SettableFuture<?> future = SettableFuture.create();
        future.addListener(() -> semaphore.release(1), directExecutor());
        futures.add(future);/*from   w ww .j  av a  2s. co  m*/
    }
    ListenableFuture<?> anyComplete = whenAnyCompleteCancelOthers(futures);
    futures.get(futureCount / 2).set(null);
    semaphore.acquireUninterruptibly(futureCount);
    anyComplete.get();
}

From source file:com.codeabovelab.dm.cluman.cluster.docker.management.ProcessEventProcessor.java

@Override
public void processResponseStream(StreamContext<ProcessEvent> context) {
    Consumer<ProcessEvent> watcher = context.getWatcher();
    InputStream response = context.getStream();
    SettableFuture<Boolean> interrupter = context.getInterrupter();
    interrupter.addListener(() -> Thread.currentThread().interrupt(), MoreExecutors.directExecutor());
    try (FrameReader frameReader = new FrameReader(response)) {

        Frame frame = frameReader.readFrame();
        while (frame != null && !interrupter.isDone()) {
            try {
                ProcessEvent.watchRaw(watcher, frame.getMessage(), false);
            } catch (Exception e) {
                LOG.error("Cannot read body", e);
            } finally {
                frame = frameReader.readFrame();
            }/*from  w  w w .  ja va  2  s .  co  m*/
        }
    } catch (Exception t) {
        LOG.error("Cannot close reader", t);
    }

}

From source file:com.codeabovelab.dm.cluman.cluster.docker.management.JsonStreamProcessor.java

@Override
public void processResponseStream(StreamContext<T> context) {
    Consumer<T> watcher = context.getWatcher();
    InputStream response = context.getStream();
    final Thread thread = Thread.currentThread();
    SettableFuture<Boolean> interrupter = context.getInterrupter();
    interrupter.addListener(() -> thread.interrupt(), MoreExecutors.directExecutor());
    try {//from  w  ww.  j a v a 2s.c om
        JsonParser jp = JSON_FACTORY.createParser(response);
        Boolean closed = jp.isClosed();
        JsonToken nextToken = jp.nextToken();
        while (!closed && nextToken != null && nextToken != JsonToken.END_OBJECT && !interrupter.isDone()) {
            try {
                ObjectNode objectNode = OBJECT_MAPPER.readTree(jp);
                // exclude empty item serialization into class #461
                if (!objectNode.isEmpty(null)) {
                    T next = OBJECT_MAPPER.treeToValue(objectNode, clazz);
                    LOG.trace("Monitor value: {}", next);
                    watcher.accept(next);
                }
            } catch (Exception e) {
            }

            closed = jp.isClosed();
            nextToken = jp.nextToken();
        }
    } catch (Throwable t) {
        throw Throwables.asRuntime(t);
    } finally {
        try {
            response.close();
        } catch (IOException e) {
            LOG.error("Can't close stream", e);

        }
    }

}

From source file:org.openqa.selenium.safari.WebSocketConnection.java

/**
 * Sends a text frame./*from   w  w  w . j  av  a2 s .c  om*/
 *
 * @param data The frame data.
 * @return A future that will resolve with a response from the driver.
 * @throws IllegalStateException If the underlying connection is closed or if there is
 *     already a pending response.
 */
public ListenableFuture<String> send(String data) {
    checkChannel();

    final SettableFuture<String> response = SettableFuture.create();
    response.addListener(new Runnable() {
        @Override
        public void run() {
            pendingResponse.compareAndSet(response, null);
        }
    }, MoreExecutors.directExecutor());

    if (pendingResponse.compareAndSet(null, response)) {
        TextWebSocketFrame frame = new TextWebSocketFrame(data);
        channel.write(frame).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    response.setException(future.getCause());
                }
            }
        });
        return response;
    }

    throw new IllegalStateException("Currently awaiting a response to a previous message");
}

From source file:io.prestosql.execution.FutureStateChange.java

public ListenableFuture<T> createNewListener() {
    SettableFuture<T> listener = SettableFuture.create();
    synchronized (listeners) {
        listeners.add(listener);// www .j  av a2s  . c om
    }

    // remove the listener when the future completes
    listener.addListener(() -> {
        synchronized (listeners) {
            listeners.remove(listener);
        }
    }, directExecutor());

    return listener;
}

From source file:com.yahoo.yqlplus.engine.internal.java.runtime.TimeoutHandler.java

public <T> ListenableFuture<T> withTimeout(final ListenableFuture<T> source, long timeout,
        TimeUnit timeoutUnits) {/*from   ww w  .ja  v a  2 s .  c  o  m*/
    if (timeout != 0) {
        final SettableFuture<T> result = SettableFuture.create();
        final Future<?> scheduledFuture = timers
                .schedule(new TimeoutTask<T>(source, result, timeout, timeoutUnits), timeout, timeoutUnits);
        result.addListener(new Runnable() {
            @Override
            public void run() {
                scheduledFuture.cancel(false);
                if (result.isCancelled()) {
                    source.cancel(true);
                }
            }
        }, MoreExecutors.sameThreadExecutor());
        Futures.addCallback(source, new FutureCallback<T>() {
            @Override
            public void onSuccess(T out) {
                scheduledFuture.cancel(false);
                result.set(out);
            }

            @Override
            public void onFailure(Throwable t) {
                scheduledFuture.cancel(false);
                result.setException(t);
            }
        });
        return scoper.scopeCallbacks(result);
    } else {
        return source;
    }
}

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

private SettableFuture<?> closeEventLoops(SettableFuture<?> previousCloseJob) {
    final SettableFuture<?> future = SettableFuture.create();
    previousCloseJob.addListener(new Runnable() {
        @Override/*from w w  w. j  a v a  2s.c  o  m*/
        public void run() {
            eventLoopTrunk.close().addListener(new Runnable() {
                @Override
                public void run() {
                    future.set(null);
                }
            }, MoreExecutors.directExecutor());
        }
    }, MoreExecutors.directExecutor());
    return future;
}

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

private SettableFuture<?> closeGateways(SettableFuture<?> previousCloseJob) {
    final SettableFuture<?> future = SettableFuture.create();
    previousCloseJob.addListener(new Runnable() {
        @Override//w  w  w .j a va2  s  . c o m
        public void run() {
            final AtomicInteger closeGwCnt = new AtomicInteger(gwMap.size());

            if (gwMap.isEmpty()) {
                future.set(null);
                return;
            }

            for (Gateway gw : gwMap.values()) {
                delGw(gw.getId(), gw.getIp(), gw.getPort()).addListener(new Runnable() {
                    @Override
                    public void run() {
                        if (closeGwCnt.decrementAndGet() == 0) {
                            future.set(null);
                        }
                    }
                }, MoreExecutors.directExecutor());
            }
        }
    }, MoreExecutors.directExecutor());

    return future;
}