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

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

Introduction

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

Prototype

@Override
    public boolean cancel(boolean mayInterruptIfRunning) 

Source Link

Usage

From source file:dk.ilios.spanner.internal.ExperimentingSpannerRun.java

public static <T> ImmutableList<ListenableFuture<T>> inCompletionOrder(
        Iterable<? extends ListenableFuture<? extends T>> futures) {
    final ConcurrentLinkedQueue<SettableFuture<T>> delegates = Queues.newConcurrentLinkedQueue();
    ImmutableList.Builder<ListenableFuture<T>> listBuilder = ImmutableList.builder();
    Executor executor = MoreExecutors.sameThreadExecutor();
    for (final ListenableFuture<? extends T> future : futures) {
        SettableFuture<T> delegate = SettableFuture.create();
        // Must make sure to add the delegate to the queue first in case the future is already done
        delegates.add(delegate);//from   ww w  .  j ava 2s . co m
        future.addListener(new Runnable() {
            @Override
            public void run() {
                SettableFuture<T> delegate = delegates.remove();
                try {
                    delegate.set(Uninterruptibles.getUninterruptibly(future));
                } catch (ExecutionException e) {
                    delegate.setException(e.getCause());
                } catch (CancellationException e) {
                    delegate.cancel(true);
                }
            }
        }, executor);
        listBuilder.add(delegate);
    }
    return listBuilder.build();
}

From source file:org.opendaylight.openflowplugin.impl.util.DeviceInitializationUtils.java

private static void addNodeToOperDS(final DeviceContext deviceContext, final SettableFuture<Void> future) {
    Preconditions.checkArgument(deviceContext != null);
    final DeviceState deviceState = deviceContext.getDeviceState();
    final NodeBuilder nodeBuilder = new NodeBuilder().setId(deviceState.getNodeId())
            .setNodeConnector(Collections.<NodeConnector>emptyList());
    try {// w w w.j a  v a2  s  . c o  m
        deviceContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL,
                deviceState.getNodeInstanceIdentifier(), nodeBuilder.build());
    } catch (final Exception e) {
        LOG.warn("Failed to write node {} to DS ", deviceState.getNodeId(), e);
        future.cancel(true);
    }
}

From source file:io.crate.jobs.ESJobContext.java

@Override
protected void innerKill(@Nonnull Throwable t) {
    for (SettableFuture<Long> resultFuture : resultFutures) {
        resultFuture.cancel(true);
    }//from   ww w .j av a  2s  .co m
}

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

/**
 * Closes this connection. Any pending responses will be canceled.
 *///from  w ww.  j ava 2  s  .  c o  m
public void close() {
    SettableFuture<String> pending = pendingResponse.getAndSet(null);
    channel.write(new CloseWebSocketFrame()).addListener(ChannelFutureListener.CLOSE);
    if (null != pending) {
        pending.cancel(true);
    }
}

From source file:com.android.camera.one.v2.initialization.CaptureSessionCreator.java

/**
 * Asynchronously creates a capture session, returning a future to it.
 *
 * @param surfaces The set of output surfaces for the camera capture
 *            session.//from  w w  w. ja v  a 2  s.  co  m
 * @return A Future for the camera capture session.
 */
public ListenableFuture<CameraCaptureSessionProxy> createCaptureSession(List<Surface> surfaces) {
    final SettableFuture<CameraCaptureSessionProxy> sessionFuture = SettableFuture.create();
    try {
        mDevice.createCaptureSession(surfaces, new CameraCaptureSessionProxy.StateCallback() {
            @Override
            public void onActive(CameraCaptureSessionProxy session) {
                // Ignore.
            }

            @Override
            public void onConfigureFailed(CameraCaptureSessionProxy session) {
                sessionFuture.cancel(true);
                session.close();
            }

            @Override
            public void onConfigured(CameraCaptureSessionProxy session) {
                boolean valueSet = sessionFuture.set(session);
                if (!valueSet) {
                    // If the future was already marked with cancellation or
                    // an exception, close the session.
                    session.close();
                }
            }

            @Override
            public void onReady(CameraCaptureSessionProxy session) {
                // Ignore.
            }

            @Override
            public void onClosed(CameraCaptureSessionProxy session) {
                sessionFuture.cancel(true);
                session.close();
            }
        }, mCameraHandler);
    } catch (CameraAccessException e) {
        sessionFuture.setException(e);
    }
    return sessionFuture;
}

From source file:com.continuuity.weave.internal.kafka.client.SimpleKafkaClient.java

private <V> ChannelFutureListener getPublishChannelFutureListener(final SettableFuture<V> result,
        final V resultObj, final ConnectionPool.ConnectionReleaser releaser) {
    return new ChannelFutureListener() {
        @Override/*ww w .j a va2  s .c om*/
        public void operationComplete(ChannelFuture future) throws Exception {
            try {
                if (future.isSuccess()) {
                    result.set(resultObj);
                } else if (future.isCancelled()) {
                    result.cancel(true);
                } else {
                    result.setException(future.getCause());
                }
            } finally {
                releaser.release();
            }
        }
    };
}

From source file:co.cask.cdap.app.runtime.spark.SparkRuntimeService.java

/**
 * Creates a {@link ListenableFuture} that is cancelled.
 *//*from w w  w  . jav a  2  s. c o  m*/
private <V> ListenableFuture<V> immediateCancelledFuture() {
    SettableFuture<V> future = SettableFuture.create();
    future.cancel(true);
    return future;
}

From source file:org.usrz.libs.utils.concurrent.SimpleExecutor.java

public <T> NotifyingFuture<T> call(Callable<T> callable) {
    final SettableFuture<T> settableFuture = SettableFuture.create();

    final Future<T> executingFuture = executor.submit(() -> {
        try {/*from  w w w . j a v a2s .  com*/
            final T result = callable.call();
            settableFuture.set(result);
            return result;
        } catch (Throwable throwable) {
            settableFuture.setException(throwable);
            throw new Exception(throwable);
        }
    });

    return new NotifyingFuture<T>() {

        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            if (executingFuture.cancel(mayInterruptIfRunning)) {
                settableFuture.cancel(mayInterruptIfRunning);
                return true;
            } else {
                return false;
            }
        }

        @Override
        public boolean isCancelled() {
            return settableFuture.isCancelled();
        }

        @Override
        public boolean isDone() {
            return settableFuture.isCancelled();
        }

        @Override
        public T get() throws InterruptedException, ExecutionException {
            return settableFuture.get();
        }

        @Override
        public T get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            return settableFuture.get(timeout, unit);
        }

        @Override
        public NotifyingFuture<T> withConsumer(Consumer<Future<T>> consumer) {
            settableFuture.addListener(() -> consumer.accept(settableFuture), notifier);
            return this;
        }

    };
}

From source file:org.opendaylight.openflowplugin.openflow.md.core.HandshakeManagerImpl.java

/**
 * send hello reply without versionBitmap
 * @param helloVersion initial hello version for openflow connection negotiation
 * @param helloXid transaction id/*from   w  w  w.  j  a  v  a  2 s.c  om*/
 * @throws Exception
 */
private ListenableFuture<Void> sendHelloMessage(Short helloVersion, final Long helloXid) throws Exception {

    HelloInput helloInput = MessageFactory.createHelloInput(helloVersion, helloXid, versionOrder);

    final SettableFuture<Void> resultFtr = SettableFuture.create();

    LOG.debug("sending hello message: version{}, xid={}, version bitmap={}", helloVersion, helloXid,
            MessageFactory.digVersions(helloInput.getElements()));

    Future<RpcResult<Void>> helloResult = connectionAdapter.hello(helloInput);

    ListenableFuture<RpcResult<Void>> rpcResultListenableFuture = JdkFutureAdapters
            .listenInPoolThread(helloResult);
    Futures.addCallback(rpcResultListenableFuture, new FutureCallback<RpcResult<Void>>() {
        @Override
        public void onSuccess(RpcResult<Void> result) {
            if (result.isSuccessful()) {
                LOG.debug("hello successfully sent, xid={}, addr={}", helloXid,
                        connectionAdapter.getRemoteAddress());
                resultFtr.set(null);
            } else {
                for (RpcError error : result.getErrors()) {
                    LOG.debug("hello sending failed [{}]: i:{} s:{} m:{}, addr:{}", helloXid, error.getInfo(),
                            error.getSeverity(), error.getMessage(), connectionAdapter.getRemoteAddress());
                    if (error.getCause() != null) {
                        LOG.trace("DETAIL of sending hello failure", error.getCause());
                    }
                }
                resultFtr.cancel(false);
                handshakeListener.onHandshakeFailure();
            }
        }

        @Override
        public void onFailure(Throwable t) {
            LOG.warn("sending of hello failed seriously [{}, addr:{}]: {}", helloXid,
                    connectionAdapter.getRemoteAddress(), t.getMessage());
            LOG.trace("DETAIL of sending of hello failure:", t);
            resultFtr.cancel(false);
            handshakeListener.onHandshakeFailure();
        }
    });
    LOG.trace("sending hello message [{}] - result hooked ..", helloXid);
    return resultFtr;
}

From source file:org.apache.twill.internal.zookeeper.ReentrantDistributedLock.java

/**
 * Executes the lock acquisition process. This corresponds to step 2-5 of the distributed lock receipt.
 *///w ww  .j  a  v a2 s .  co m
private void doAcquire(final SettableFuture<String> completion, final boolean waitForLock, final String guid,
        @Nullable final String lockPath) {
    // Step 2. Get all children under the lock parent.
    Futures.addCallback(zkClient.getChildren(path), new FutureCallback<NodeChildren>() {

        @Override
        public void onSuccess(NodeChildren children) {
            // Find the lock node in case the creation step failed by matching the guid
            // See "Recoverable Errors and the GUID" in the ZooKeeper guide
            final String lockNode = lockPath == null ? findLockNode(children.getChildren(), guid) : lockPath;
            if (lockNode == null) {
                // If not able to find the lock node, fail the locking procedure.
                completion.setException(new IllegalStateException("Failed to acquire lock").fillInStackTrace());
                return;
            }

            if (lockPath == null) {
                // If lock node was not determined in step 1 due to connection loss exception, need to add the
                // node deletion handler in here after the actual lockNode is determined.
                deleteNodeOnFailure(completion, lockNode);
            }

            // Find the node to watch, which is the one with the largest id that is smaller than currentId
            // If the current id is the smallest one, nodeToWatch will be null
            final String nodeToWatch = findNodeToWatch(children, lockNode, guid);

            // Step 3a. lockNode is the lowest, hence this become lock owner.
            if (nodeToWatch == null) {
                // Acquired lock
                completion.set(lockNode);
            } else if (!waitForLock) {
                // This is for the case of tryLock() without timeout.
                completion.cancel(true);
            }
            // If the lock acquisition is completed, due to whatever reason, we don't need to watch for any other nodes
            if (completion.isDone()) {
                return;
            }

            // Step 3b and 4. See if the the next lowest sequence ID exists. If it does, leave a watch
            // Use getData() instead of exists() to avoid leaking Watcher resources (if the node is gone, there will
            // be a watch left on the ZK server if exists() is used).
            OperationFuture<NodeData> getDataFuture = zkClient.getData(nodeToWatch, new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    if (!completion.isDone()) {
                        // If the watching node changed, go to step 2.
                        doAcquire(completion, waitForLock, guid, lockNode);
                    }
                }
            });

            // Step 5. Depends on the exists call result, either go to step 2 if the nodeToWatch is gone or just
            // let the watcher to trigger step 2 when there is change to the nodeToWatch.
            Futures.addCallback(getDataFuture, new FutureCallback<NodeData>() {
                @Override
                public void onSuccess(NodeData nodeData) {
                    // No-op
                }

                @Override
                public void onFailure(Throwable t) {
                    // See if the failure is due to node not exists. If that's the case, go to step 2.
                    if (t instanceof KeeperException.NoNodeException && !completion.isDone()) {
                        doAcquire(completion, waitForLock, guid, lockNode);
                    } else {
                        // If failed due to something else, fail the lock acquisition.
                        completion.setException(t);
                    }
                }
            });
        }

        @Override
        public void onFailure(Throwable t) {
            if (lockPath != null) {
                completion.setException(t);
            } else {
                doAcquire(completion, waitForLock, guid, null);
            }
        }
    });
}