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:com.facebook.swift.service.ThriftClientManager.java

public <T, C extends NiftyClientChannel> ListenableFuture<T> createClient(
        final NiftyClientConnector<C> connector, final Class<T> type, final Duration connectTimeout,
        final Duration readTimeout, final Duration writeTimeout, final String clientName,
        HostAndPort socksProxy) {//w w  w  .j  a v a  2  s  . c  o m
    NiftyClientChannel channel = null;
    try {
        final SettableFuture<T> clientFuture = SettableFuture.create();
        ListenableFuture<C> connectFuture = niftyClient.connectAsync(connector, connectTimeout, readTimeout,
                writeTimeout, this.toSocksProxyAddress(socksProxy));
        Futures.addCallback(connectFuture, new FutureCallback<C>() {
            @Override
            public void onSuccess(C result) {
                NiftyClientChannel channel = result;

                if (readTimeout.toMillis() > 0) {
                    channel.setReceiveTimeout(readTimeout);
                }
                if (writeTimeout.toMillis() > 0) {
                    channel.setSendTimeout(writeTimeout);
                }
                clientFuture.set(createClient(channel, type,
                        Strings.isNullOrEmpty(clientName) ? connector.toString() : clientName));
            }

            @Override
            public void onFailure(Throwable t) {
                clientFuture.setException(t);
            }
        });
        return clientFuture;
    } catch (RuntimeException | Error e) {
        if (channel != null) {
            channel.close();
        }
        throw e;
    }
}

From source file:org.apache.bookkeeper.bookie.LedgerDescriptorImpl.java

/**
 * Log the fence ledger entry in Journal so that we can rebuild the state.
 * @param journal log the fence entry in the Journal
 * @return A future which will be satisfied when add entry to journal complete
 *//*from www  .j a v a  2  s . c  o  m*/
private SettableFuture<Boolean> logFenceEntryInJournal(Journal journal) {
    SettableFuture<Boolean> result;
    synchronized (this) {
        result = logFenceResult = SettableFuture.create();
    }
    ByteBuf entry = createLedgerFenceEntry(ledgerId);
    try {
        journal.logAddEntry(entry, false /* ackBeforeSync */, (rc, ledgerId, entryId, addr, ctx) -> {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Record fenced state for ledger {} in journal with rc {}", ledgerId,
                        BKException.codeLogger(rc));
            }
            if (rc == 0) {
                fenceEntryPersisted.compareAndSet(false, true);
                result.set(true);
            } else {
                result.set(false);
            }
        }, null);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        result.setException(e);
    }
    return result;
}

From source file:io.crate.protocols.postgres.BulkPortal.java

private ListenableFuture<Void> executeBulk(Executor executor, Plan plan, final UUID jobId,
        final StatsTables statsTables) {
    final SettableFuture<Void> future = SettableFuture.create();
    Futures.addCallback(executor.executeBulk(plan), new FutureCallback<List<Long>>() {
        @Override/*w w w.  j a  va 2s . co m*/
        public void onSuccess(@Nullable List<Long> result) {
            assert result != null && result.size() == resultReceivers
                    .size() : "number of result must match number of rowReceivers";

            Long[] cells = new Long[1];
            RowN row = new RowN(cells);
            for (int i = 0; i < result.size(); i++) {
                cells[0] = result.get(i);
                ResultReceiver resultReceiver = resultReceivers.get(i);
                resultReceiver.setNextRow(row);
                resultReceiver.allFinished();
            }
            future.set(null);
            statsTables.logExecutionEnd(jobId, null);
        }

        @Override
        public void onFailure(Throwable t) {
            for (ResultReceiver resultReceiver : resultReceivers) {
                resultReceiver.fail(t);
            }
            future.setException(t);
            statsTables.logExecutionEnd(jobId, Exceptions.messageOf(t));

        }
    });
    return future;
}

From source file:org.opendaylight.ofconfig.southbound.impl.api.ver12.helper.AbstractOfconfigVer12HandlerHelper.java

@Override
public Future<RpcResult<Void>> doDelete(T request) {
    SettableFuture<RpcResult<Void>> resultFuture = SettableFuture.create();
    try {/* ww  w.j  a va 2s .  c o m*/
        String netconfigId = getNetconfigTopoNodeId(request);
        Optional<CapableSwitch> capableSwitchOptional = getDeviceCapableSwitch(netconfigId);
        if (!capableSwitchOptional.isPresent()) {
            return buildNotFoundResult(netconfigId);
        }

        CapableSwitch newCapableSwitch = deleteCapableSwitch(capableSwitchOptional.get(), request);

        updateDeviceCapableSwitch(newCapableSwitch, netconfigId);

        updateOfOfconfig(netconfigId);

        resultFuture.set(RpcResultBuilder.<Void>success().build());

    } catch (Exception e) {
        String netconfigId = getNetconfigTopoNodeId(request);
        logger.error("delete operation occurr error,netconf topo node id:{}", netconfigId, e);
        resultFuture.set(RpcResultBuilder.<Void>failed().withError(ErrorType.APPLICATION,
                "delete operation occurr error,netconf topo node id:{}", netconfigId).build());

    }

    return resultFuture;
}

From source file:c5db.replication.ReplicatorService.java

@Override
public ListenableFuture<Replicator> createReplicator(final String quorumId, final Collection<Long> peers) {
    final SettableFuture<Replicator> future = SettableFuture.create();

    ListenableFuture<ReplicatorLog> logFuture = logModule.getReplicatorLog(quorumId);

    C5Futures.addCallback(logFuture, (ReplicatorLog log) -> {
        Replicator replicator = createReplicatorWithLog(log, quorumId, peers);
        future.set(replicator);//from  w  w  w  .  ja v a2 s  . c  om
    }, future::setException, fiber);

    return future;
}

From source file:eu.esdihumboldt.hale.ui.util.source.CompilingSourceViewer.java

/**
 * Get the compilation result./* w  ww.  j  av  a2s .  c  om*/
 * 
 * @return a future reference to the compilation result, the actual
 *         compilation result may be <code>null</code> if the compilation
 *         failed
 */
public ListenableFuture<C> getCompiled() {
    SettableFuture<C> result = SettableFuture.create();
    if (!compilationEnabled) {
        result.set(null);
        return result;
    }

    changeLock.lock();
    try {
        if (changed) {
            // compilation result is not up-to-date
            toUpdate.add(result);
        } else {
            result.set(compiled);
        }
    } finally {
        changeLock.unlock();
    }

    return result;
}

From source file:org.apache.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 ww.jav a2  s  .  c  o m*/
public SettableFuture<T> execAsync(final Statement statement, final T inputs,
        final AsyncResultHandler<T> handler) {
    final SettableFuture<T> settableFuture = SettableFuture.create();
    pending.incrementAndGet();
    ResultSetFuture future = session.executeAsync(statement);
    Futures.addCallback(future, new FutureCallback<ResultSet>() {
        public void release() {
            pending.decrementAndGet();
        }

        @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:com.google.jimfs.JimfsAsynchronousFileChannel.java

/**
 * Immediate future indicating that the channel is closed.
 *//*  ww w. j  a v  a  2  s  .co m*/
private static <V> ListenableFuture<V> closedChannelFuture() {
    SettableFuture<V> future = SettableFuture.create();
    future.setException(new ClosedChannelException());
    return future;
}

From source file:org.wso2.andes.kernel.disruptor.inbound.InboundKernelOpsEvent.java

/**
 * Update event to start message delivery event
 * @param messagingEngine MessagingEngine
 *//*from w  w w .j  av a2  s  .c  o m*/
public void prepareForStartMessageDelivery(MessagingEngine messagingEngine) {
    eventType = EventType.START_MESSAGE_DELIVERY_EVENT;
    this.messagingEngine = messagingEngine;
    taskStatus = SettableFuture.create();
}

From source file:com.facebook.buck.remoteexecution.util.MultiThreadedBlobUploader.java

private ListenableFuture<Void> enqueue(ImmutableMap<Digest, UploadDataSupplier> data) {
    ImmutableList.Builder<ListenableFuture<Void>> futures = ImmutableList.builder();
    for (Entry<Digest, UploadDataSupplier> entry : data.entrySet()) {
        Digest digest = entry.getKey();//  w  ww.  j  a v a  2  s  .  c om
        ListenableFuture<Void> resultFuture = pendingUploads.computeIfAbsent(digest.getHash(), hash -> {
            if (containedHashes.contains(hash)) {
                return Futures.immediateFuture(null);
            }
            SettableFuture<Void> future = SettableFuture.create();
            waitingMissingCheck.add(new PendingUpload(new UploadData(digest, entry.getValue()), future));
            return Futures.transform(future, ignore -> {
                // If the upload was successful short circuit for future requests.
                containedHashes.add(digest.getHash());
                return null;
            }, directExecutor());
        });
        Futures.addCallback(resultFuture, MoreFutures.finallyCallback(() -> {
            pendingUploads.remove(digest.getHash());
        }), directExecutor());
        futures.add(resultFuture);
        uploadService.submit(this::processUploads);
    }
    return Futures.whenAllSucceed(futures.build()).call(() -> null, directExecutor());
}