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:com.mirantis.opendaylight.Retrier.java

private void doRetry(SettableFuture<V> promise, int attempt) {
    if (attempt > 0) {
        try {//from   ww w. j av a2 s . c  om
            Futures.addCallback(block.get(), new FutureCallback<V>() {
                @Override
                public void onSuccess(V value) {
                    promise.set(value);
                }

                @Override
                public void onFailure(Throwable t) {
                    if (condition.apply(t)) {
                        log.debug("Retrying", t);
                        doRetry(promise, attempt - 1);
                    } else {
                        log.debug(t.getMessage(), t);
                        promise.setException(t);
                    }
                }
            }, executor);
        } catch (RuntimeException e) {
            log.debug("Couldn't get code block to retrying", e);
            promise.setException(e);
        }
    } else {
        promise.setException(new RuntimeException("Number of attempts exeeded"));
    }
}

From source file:com.facebook.buck.util.concurrent.ResourcePool.java

@Override
public synchronized void close() {
    Preconditions.checkState(!closing.get());
    closing.set(true);//from  w  w  w.java 2s .  com

    // Unblock all waiting requests.
    for (SettableFuture<Void> request : resourceRequests) {
        request.set(null);
    }
    resourceRequests.clear();

    // Any processing that is currently taking place will be allowed to complete (as it won't notice
    // `closing` is true.
    // Any scheduled (but not executing) resource requests should notice `closing` is true and
    // mark themselves as cancelled.
    // Therefore `closeFuture` should allow us to wait for any resources that are in use.
    ListenableFuture<List<Object>> closeFuture = Futures.successfulAsList(pendingWork);

    // As silly as it seems this is the only reliable way to make sure we run the shutdown code.
    // Reusing an external executor means we run the risk of it being shut down before the cleanup
    // future is ready to run (which causes it to never run).
    // Using a direct executor means we run the chance of executing shutdown synchronously (which
    // we try to avoid).
    final ExecutorService executorService = MostExecutors.newSingleThreadExecutor("resource shutdown");

    // It is possible that more requests for work are scheduled at this point, however they should
    // all early-out due to `closing` being set to true, so we don't really care about those.
    shutdownFuture = Futures.transformAsync(closeFuture, new AsyncFunction<List<Object>, Void>() {
        @Override
        public ListenableFuture<Void> apply(List<Object> input) throws Exception {
            synchronized (ResourcePool.this) {
                if (parkedResources.size() != createdResources.size()) {
                    LOG.error("Whoops! Some resource are still in use during shutdown.");
                }
                // Now that pending work is done we can close all resources.
                for (R resource : createdResources) {
                    resource.close();
                }
                if (!resourceRequests.isEmpty()) {
                    LOG.error("Error shutting down ResourcePool: "
                            + "there should be no enqueued resource requests.");
                }
            }
            executorService.shutdown();
            return Futures.immediateFuture(null);
        }
    }, executorService);
}

From source file:org.opendaylight.lispflowmapping.netconf.impl.LispDeviceNetconfConnector.java

private boolean verifyBuildInput(final BuildConnectorInput req, SettableFuture<RpcResult<Void>> futureResult) {
    if (req.getInstance() == null) {
        LOG.error("Instance name not initialized");
        futureResult.set(RpcResultBuilder.<Void>failed()
                .withError(ErrorType.APPLICATION, "exception", "Instance name not initialized").build());
        return false;
    }/* w w  w  .j ava  2 s .co m*/

    if (req.getAddress() == null) {
        LOG.error("IP address not initialized");
        futureResult.set(RpcResultBuilder.<Void>failed()
                .withError(ErrorType.APPLICATION, "exception", "IP address not initialized").build());
        return false;
    }

    if (req.getPort() == null) {
        LOG.error("Port not initialized");
        futureResult.set(RpcResultBuilder.<Void>failed()
                .withError(ErrorType.APPLICATION, "exception", "Port not initialized").build());
        return false;
    }

    if (req.getUsername() == null) {
        LOG.error("Username not initialized");
        futureResult.set(RpcResultBuilder.<Void>failed()
                .withError(ErrorType.APPLICATION, "exception", "Username not initialized").build());
        return false;
    }

    if (req.getPassword() == null) {
        LOG.error("Password not initialized");
        futureResult.set(RpcResultBuilder.<Void>failed()
                .withError(ErrorType.APPLICATION, "exception", "Password not initialized").build());
        return false;
    }

    return true;
}

From source file:com.android.build.gradle.internal.process.GradleProcessExecutor.java

@NonNull
@Override/*from  ww w .j  a  v a  2  s . c  o  m*/
public ListenableFuture<ProcessResult> submit(@NonNull final ProcessInfo processInfo,
        @NonNull final ProcessOutputHandler processOutputHandler) {
    final SettableFuture<ProcessResult> res = SettableFuture.create();
    new Thread() {
        @Override
        public void run() {
            try {
                ProcessResult result = execute(processInfo, processOutputHandler);
                res.set(result);
            } catch (Exception e) {
                res.setException(e);
            }
        }
    }.start();

    return res;
}

From source file:com.datastax.driver.core.EventDebouncer.java

void deliverEvents() {
    if (state == State.STOPPED) {
        completeAllPendingFutures();/*from w  w w . ja  v  a 2  s  .  co  m*/
        return;
    }
    final List<T> toDeliver = Lists.newArrayList();
    final List<SettableFuture<Void>> futures = Lists.newArrayList();

    Entry<T> entry;
    // Limit the number of events we dequeue, to avoid an infinite loop if the queue starts filling faster than we can consume it.
    int count = 0;
    while (++count <= maxQueuedEvents && (entry = this.events.poll()) != null) {
        toDeliver.add(entry.event);
        futures.add(entry.future);
    }
    eventCount.addAndGet(-toDeliver.size());

    if (toDeliver.isEmpty()) {
        logger.trace("{} debouncer: no events to deliver", name);
    } else {
        logger.trace("{} debouncer: delivering {} events", name, toDeliver.size());
        ListenableFuture<?> delivered = callback.deliver(toDeliver);
        Futures.addCallback(delivered, new FutureCallback<Object>() {
            @Override
            public void onSuccess(Object result) {
                for (SettableFuture<Void> future : futures)
                    future.set(null);
            }

            @Override
            public void onFailure(Throwable t) {
                for (SettableFuture<Void> future : futures)
                    future.setException(t);
            }
        });
    }

    // If we didn't dequeue all events (or new ones arrived since we did), make sure we eventually
    // process the remaining events, because eventReceived might have skipped the delivery
    if (eventCount.get() > 0)
        scheduleDelayedDelivery();
}

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

@Override
protected void init() {
    compileJob = new Job("Compile") {

        @Override//from   w w  w . j a  va2  s  . co m
        public boolean shouldRun() {
            return compilationEnabled;
        }

        @Override
        public boolean shouldSchedule() {
            return compilationEnabled;
        }

        @Override
        protected IStatus run(IProgressMonitor monitor) {
            String content;
            changeLock.lock();
            try {
                if (!changed) {
                    return Status.OK_STATUS;
                }
                IDocument doc = getDocument();
                if (doc != null) {
                    content = doc.get();
                } else {
                    content = null;
                }
                changed = false;
            } finally {
                changeLock.unlock();
            }

            C result = null;
            if (content != null) {
                try {
                    // this is the potentially long running stuff
                    result = compile(content);
                } catch (Exception e) {
                    // ignore, but log
                    log.warn("Error compiling document content", e);
                }
            }

            boolean notify = false;
            C previous = null;
            changeLock.lock();
            try {
                /*
                 * Only notify listeners if the document was not changed in
                 * the meantime.
                 */
                notify = !changed;
                if (notify) {
                    // set result
                    previous = compiled;
                    compiled = result;

                    // set result for futures
                    for (SettableFuture<C> future : toUpdate) {
                        future.set(result);
                    }
                    toUpdate.clear();
                }
            } finally {
                changeLock.unlock();
            }

            if (notify) {
                // notify listeners
                PropertyChangeEvent event = new PropertyChangeEvent(CompilingSourceViewer.this,
                        PROPERTY_COMPILED, previous, result);
                notifyOnPropertyChange(event);
            }

            return Status.OK_STATUS;
        }
    };
    compileJob.setSystem(true);
    compileJob.setRule(new ExclusiveSchedulingRule(compileJob));

    super.init();
}

From source file:com.android.builder.internal.aapt.AbstractProcessExecutionAapt.java

@NonNull
@Override//from w w w .  j  av  a2 s  .  co  m
public ListenableFuture<File> compile(@NonNull File file, @NonNull File output) throws AaptException {
    Preconditions.checkArgument(file.isFile(), "!file.isFile()");
    Preconditions.checkArgument(output.isDirectory(), "!output.isDirectory()");

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

    CompileInvocation compileInvocation = makeCompileProcessBuilder(file, output);
    if (compileInvocation == null) {
        result.set(null);
        return result;
    }

    ProcessInfo processInfo = compileInvocation.builder.createProcess();
    ListenableFuture<ProcessResult> execResult = mProcessExecutor.submit(processInfo, mProcessOutputHandler);

    Futures.addCallback(execResult, new FutureCallback<ProcessResult>() {
        @Override
        public void onSuccess(ProcessResult processResult) {
            try {
                processResult.rethrowFailure().assertNormalExitValue();
                result.set(compileInvocation.outputFile);
            } catch (Exception e) {
                result.setException(e);
            }
        }

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

    return result;
}

From source file:com.facebook.presto.operator.exchange.LocalExchangeMemoryManager.java

public void setNoBlockOnFull() {
    blockOnFull.set(false);//ww  w  .  j a  v  a2  s .  com

    SettableFuture<?> future;
    synchronized (this) {
        if (notFullFuture.isDone()) {
            return;
        }

        future = notFullFuture;
        notFullFuture = NOT_FULL;
    }

    // complete future outside of lock since this can invoke callbacks
    future.set(null);
}

From source file:org.opendaylight.centinel.impl.subscribe.SubscriberImpl.java

@Override
public Future<RpcResult<SubscribeTestOutput>> subscribeTest(SubscribeTestInput input) {
    // TODO Auto-generated method stub
    final SettableFuture<RpcResult<SubscribeTestOutput>> futureResult = SettableFuture.create();

    publishToURL(input.getAlertID(), input.getStreamID(), input.getMessage());

    futureResult.set(RpcResultBuilder
            .<SubscribeTestOutput>success(new SubscribeTestOutputBuilder().setStatus("SUCCESS").build())
            .build());// www  .  j a  v a2 s  .  co m
    return futureResult;
}

From source file:org.freeswitch.esl.client.internal.AbstractEslClientHandler.java

@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    if (e.getMessage() instanceof EslMessage) {
        final EslMessage message = (EslMessage) e.getMessage();
        final String contentType = message.getContentType();
        if (contentType.equals(Value.TEXT_EVENT_PLAIN) || contentType.equals(Value.TEXT_EVENT_XML)) {
            //  transform into an event
            final EslEvent eslEvent = new EslEvent(message);
            if (eslEvent.getEventName().equals("BACKGROUND_JOB")) {
                final String backgroundUuid = eslEvent.getEventHeaders().get(EslHeaders.Name.JOB_UUID);
                final SettableFuture<EslEvent> future = backgroundJobs.remove(backgroundUuid);
                if (null != future) {
                    future.set(eslEvent);
                }/*w w  w.  java 2s .c  o  m*/
            } else {
                handleEslEvent(ctx, eslEvent);
            }
        } else {
            handleEslMessage(ctx, (EslMessage) e.getMessage());
        }
    } else {
        throw new IllegalStateException("Unexpected message type: " + e.getMessage().getClass());
    }
}