List of usage examples for com.google.common.util.concurrent SettableFuture create
public static <V> SettableFuture<V> create()
From source file:org.whispersystems.websocket.WebSocketClient.java
public ListenableFuture<WebSocketResponseMessage> sendRequest(String verb, String path, Optional<byte[]> body) { long requestId = generateRequestId(); SettableFuture<WebSocketResponseMessage> future = SettableFuture.create(); pendingRequestMapper.put(requestId, future); WebSocketMessage requestMessage = messageFactory.createRequest(Optional.of(requestId), verb, path, body); try {// w ww. java 2 s . c o m remoteEndpoint.sendBytes(ByteBuffer.wrap(requestMessage.toByteArray())); } catch (IOException | WebSocketException e) { logger.debug("Write", e); pendingRequestMapper.remove(requestId); future.setException(e); } return future; }
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 w w . j a v a 2s. com*/ } ListenableFuture<?> anyComplete = whenAnyCompleteCancelOthers(futures); futures.get(futureCount / 2).set(null); semaphore.acquireUninterruptibly(futureCount); anyComplete.get(); }
From source file:org.apache.qpid.server.model.AbstractConfiguredObjectTypeFactory.java
@Override public ListenableFuture<X> createAsync(final ConfiguredObjectFactory factory, final Map<String, Object> attributes, final ConfiguredObject<?> parent) { final SettableFuture<X> returnVal = SettableFuture.create(); final X instance = createInstance(attributes, parent); final ListenableFuture<Void> createFuture = instance.createAsync(); AbstractConfiguredObject.addFutureCallback(createFuture, new FutureCallback<Void>() { @Override/* www . ja v a2 s . c o m*/ public void onSuccess(final Void result) { returnVal.set(instance); } @Override public void onFailure(final Throwable t) { returnVal.setException(t); } }, MoreExecutors.directExecutor()); return returnVal; }
From source file:io.v.baku.toolkit.blessings.ActivityBlessingsSeeker.java
public ActivityBlessingsSeeker(final Activity activity, final ErrorReporter errorReporter, final boolean seekInProgress) { mActivity = activity;/* w w w .j ava 2 s. co m*/ mErrorReporter = errorReporter; if (seekInProgress) { mCurrentSeek = SettableFuture.create(); } mPub = PublishSubject.create(); mPassiveRxBlessings = mPub.flatMap(FutureConverter::toObservable).distinctUntilChanged().replay(1) .autoConnect(); /* It might make more sense for b -> mLastBlessings = b to be an onNext before the above replay rather than a subscription (especially if we start getting OnErrorNotImplementedException or have to include a possibly redundant error reporter). However, replay, even with autoConnect(0), does not offer backpressure support unless it has subscribers. We can get around this by adding .onBackpressureBuffer(1), but if this turns out to be a better way of doing this, we should submit an issue requesting that OperatorReplay use its buffer size for backpressure. */ mPassiveRxBlessings.subscribe(b -> mLastBlessings = b); mRxBlessings = Observable.defer(() -> FutureConverter.toObservable(refreshBlessings())).ignoreElements() .concatWith(mPassiveRxBlessings); }
From source file:org.apache.twill.internal.Services.java
/** * Returns a {@link ListenableFuture} that will be completed when the given service is stopped. If the service * stopped due to error, the failure cause would be reflected in the future. * * @param service The {@link Service} to block on. * @return A {@link ListenableFuture} that will be completed when the service is stopped. *//*w w w . j a v a 2s . co m*/ public static ListenableFuture<Service.State> getCompletionFuture(Service service) { final SettableFuture<Service.State> resultFuture = SettableFuture.create(); service.addListener(new ServiceListenerAdapter() { @Override public void terminated(Service.State from) { resultFuture.set(Service.State.TERMINATED); } @Override public void failed(Service.State from, Throwable failure) { resultFuture.setException(failure); } }, Threads.SAME_THREAD_EXECUTOR); Service.State state = service.state(); if (state == Service.State.TERMINATED) { return Futures.immediateFuture(state); } else if (state == Service.State.FAILED) { return Futures .immediateFailedFuture(new IllegalStateException("Service failed with unknown exception.")); } return resultFuture; }
From source file:org.opendaylight.netconf.topology.singleton.impl.tx.NetconfReadOnlyTransaction.java
@Override public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final LogicalDatastoreType store, final YangInstanceIdentifier path) { LOG.trace("{}: Read {} via NETCONF: {}", id, store, path); final Future<Optional<NormalizedNodeMessage>> future = delegate.read(store, path); final SettableFuture<Optional<NormalizedNode<?, ?>>> settableFuture = SettableFuture.create(); final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> checkedFuture; checkedFuture = Futures.makeChecked(settableFuture, new Function<Exception, ReadFailedException>() { @Nullable/*from w ww .j av a2 s . c om*/ @Override public ReadFailedException apply(Exception cause) { return new ReadFailedException("Read from transaction failed", cause); } }); future.onComplete(new OnComplete<Optional<NormalizedNodeMessage>>() { @Override public void onComplete(final Throwable throwable, final Optional<NormalizedNodeMessage> normalizedNodeMessage) throws Throwable { if (throwable == null) { if (normalizedNodeMessage.isPresent()) { settableFuture.set(normalizedNodeMessage .transform(new Function<NormalizedNodeMessage, NormalizedNode<?, ?>>() { @Nullable @Override public NormalizedNode<?, ?> apply(final NormalizedNodeMessage input) { return input.getNode(); } })); } else { settableFuture.set(Optional.absent()); } } else { settableFuture.setException(throwable); } } }, actorSystem.dispatcher()); return checkedFuture; }
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,/* ww w .j a va 2s .co m*/ * * @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:ch.vorburger.osgi.builder.internal.SourceInstallServiceImpl.java
@Override public ListenableFuture<Bundle> installSourceBundle(File projectDirectoryOrBundleJAR) { SettableFuture<Bundle> installFuture = SettableFuture.create(); BuildServiceSingleFileOutputListener listener = singleProducedFile -> { try (InputStream inputStream = new FileInputStream(singleProducedFile)) { String location = getBundleLocation(projectDirectoryOrBundleJAR); Bundle bundle = bundleContext.getBundle(location); if (bundle == null) { LOG.info("Installing Bundle from {}", location); bundle = bundleContext.installBundle(location, inputStream); bundle.start();/*from ww w. j a v a 2 s .c om*/ } else { LOG.info("Updating Bundle from {}", location); bundle.update(inputStream); // We (possibly "re")-start here, because it's possible that // an initial (or previous) start() failed due to some bug in the bundle // and that could have meanwhile be fixed, but OSGi won't re-try starting // a bundle an update if we don't tell it to... bundle.start(); } installFuture.set(bundle); } catch (BundleException | IOException e) { LOG.error("Problem reading/installing bundle JAR: {}", singleProducedFile, e); installFuture.setException(e); } }; ListenableFuture<Void> buildFuture; if (new File(projectDirectoryOrBundleJAR, "pom.xml").exists()) { LOG.info("Found a POM in directory, will continously build with Maven: {}", projectDirectoryOrBundleJAR); buildFuture = mavenBuildService.buildContinously(projectDirectoryOrBundleJAR, "install", listener); } else if (projectDirectoryOrBundleJAR.isDirectory()) { LOG.info("Found directory (but no POM), will continously build with Gradle: {}", projectDirectoryOrBundleJAR); buildFuture = gradleBuildService.buildContinously(projectDirectoryOrBundleJAR, "build", listener); } else if (projectDirectoryOrBundleJAR.isFile() && projectDirectoryOrBundleJAR.getName().endsWith(".jar")) { LOG.info("Found JAR, will install and update on update: {}", projectDirectoryOrBundleJAR); // The JAR is already ready now, and can be started by caller: try { // NB: The default quietPeriod of 100ms is often not enough while Gradle updates the JAR and leads to ZipException, so 500ms: bundleFileWatcher = new FileWatcherBuilder().path(projectDirectoryOrBundleJAR).quietPeriodInMS(500) .listener((path, changeKind) -> { switch (changeKind) { case MODIFIED: // NB: FileWatcherBuilder invoked the listener once on start, and then on subsequent changes listener.buildSucceeded(projectDirectoryOrBundleJAR); break; case DELETED: String location = getBundleLocation(projectDirectoryOrBundleJAR); LOG.info("Uninstalling Bundle from {}", location); bundleContext.getBundle(location).uninstall(); break; default: LOG.error("Unsupported file watcher change kind, ignored: {}", changeKind); break; } System.out.println(changeKind.name() + " " + path.toString()); }).build(); buildFuture = Futures.immediateFuture(null); } catch (IOException e) { buildFuture = Futures.immediateFailedFuture(e); } // But we make sure than upon changes it gets reloaded: // TODO!!!! } else { buildFuture = Futures.immediateFailedFuture( new IllegalArgumentException("Neither a directory (with or w.o. pom.xml) nor a JAR, " + "how I am supposed to (build and) install this as an OSGi bundle: " + projectDirectoryOrBundleJAR)); } Futures.addCallback(buildFuture, new FutureCallback<Void>() { @Override public void onFailure(Throwable throwable) { // If this happens, then the listener above will never get invoked // because the (first, as it's continous) build failed before, so: installFuture.setException(throwable); } @Override public void onSuccess(Void nothing) { } }); return installFuture; }
From source file:com.facebook.buck.parser.PipelineNodeCache.java
/** * Helper for de-duping jobs against the cache. * * @param jobSupplier a supplier to use to create the actual job. * @return future describing the job. It can either be an immediate future (result cache hit), * ongoing job (job cache hit) or a new job (miss). *///from w w w .j a v a2 s .c om protected final ListenableFuture<T> getJobWithCacheLookup(final Cell cell, final K key, JobSupplier<T> jobSupplier) throws BuildTargetException { Optional<T> cacheLookupResult = cache.lookupComputedNode(cell, key); if (cacheLookupResult.isPresent()) { return Futures.immediateFuture(cacheLookupResult.get()); } ListenableFuture<T> speculativeCacheLookupResult = jobsCache.get(key); if (speculativeCacheLookupResult != null) { return speculativeCacheLookupResult; } // We use a SettableFuture to resolve any races between threads that are trying to create the // job for the given key. The SettableFuture is cheap to throw away in case we didn't "win" and // can be easily "connected" to a future that actually does work in case we did. SettableFuture<T> resultFutureCandidate = SettableFuture.create(); ListenableFuture<T> resultFutureInCache = jobsCache.putIfAbsent(key, resultFutureCandidate); if (resultFutureInCache != null) { // Another thread succeeded in putting the new value into the cache. return resultFutureInCache; } // Ok, "our" candidate future went into the jobsCache, schedule the job and 'chain' the result // to the SettableFuture, so that anyone else waiting on it will get the same result. final SettableFuture<T> resultFuture = resultFutureCandidate; try { ListenableFuture<T> nodeJob = Futures.transformAsync(jobSupplier.get(), input -> Futures.immediateFuture(cache.putComputedNodeIfNotPresent(cell, key, input))); resultFuture.setFuture(nodeJob); } catch (Throwable t) { resultFuture.setException(t); throw t; } return resultFuture; }
From source file:com.facebook.presto.operator.exchange.LocalExchangeMemoryManager.java
public synchronized ListenableFuture<?> getNotFullFuture() { // if we are full and still blocking and the current not full future is already complete, create a new one if (bufferedBytes.get() > maxBufferedBytes && blockOnFull.get() && notFullFuture.isDone()) { notFullFuture = SettableFuture.create(); }//from ww w . j ava 2 s. c om return notFullFuture; }