List of usage examples for com.google.common.util.concurrent ListenableFuture addListener
void addListener(Runnable listener, Executor executor);
From source file:com.navercorp.nbasearc.gcp.Gateway.java
ListenableFuture<?> init(SingleThreadEventLoopTrunk eventLoopTrunk, int reconnectInterval) { final SettableFuture<?> sf = SettableFuture.create(); for (int i = 0; i < concnt; i++) { cons[i] = PhysicalConnection.create(ip, port, eventLoopTrunk.roundrobinEventLoop(), this, reconnectInterval);/* www . jav a 2s . c om*/ final ListenableFuture<?> conFuture = cons[i].connect(); conFuture.addListener(new Runnable() { @Override public void run() { try { conFuture.get(); sf.set(null); } catch (InterruptedException e) { log.error("Exception occured while connecting to {}", Gateway.this, e); } catch (ExecutionException e) { log.error("Exception occured while connecting to {}", Gateway.this, e); } } }, MoreExecutors.directExecutor()); } return sf; }
From source file:io.bitsquare.trade.protocol.trade.tasks.shared.SetupPayoutTxLockTimeReachedListener.java
@Override protected void run() { try {/* w w w . j a v a2s. c om*/ runInterceptHook(); log.debug("ChainHeight/LockTime: {} / {}", processModel.getTradeWalletService().getBestChainHeight(), trade.getLockTime()); if (processModel.getTradeWalletService().getBestChainHeight() >= trade.getLockTime()) { broadcastTx(); } else { ListenableFuture<StoredBlock> blockHeightFuture = processModel.getTradeWalletService() .getBlockHeightFuture(trade.getPayoutTx()); blockHeightFuture.addListener(() -> { try { log.debug("Block height reached " + blockHeightFuture.get().getHeight()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } broadcastTx(); }, Threading.USER_THREAD::execute); } } catch (Throwable t) { failed(t); } }
From source file:org.jclouds.atmos.blobstore.strategy.FindMD5InUserMetadata.java
@Override public boolean execute(final String containerName, Object value, ListContainerOptions options) { final byte[] toSearch = objectMD5.apply(value); final BlockingQueue<Boolean> queue = new SynchronousQueue<Boolean>(); Map<String, ListenableFuture<?>> responses = Maps.newHashMap(); for (BlobMetadata md : getAllBlobMetadata.execute(containerName, options)) { final ListenableFuture<AtmosObject> future = client.headFile(containerName + "/" + md.getName()); future.addListener(new Runnable() { public void run() { try { AtmosObject object = future.get(); checkNotNull(object.getSystemMetadata(), object + " has no content metadata"); if (object.getSystemMetadata().getContentMD5() != null) { if (Arrays.equals(toSearch, object.getSystemMetadata().getContentMD5())) { queue.put(true); }//from w w w . ja v a2s . c o m } else { logger.debug("object %s has no content md5", object.getSystemMetadata().getObjectID()); } } catch (InterruptedException e) { Throwables.propagate(e); } catch (ExecutionException e) { Throwables.propagate(e); } } }, userExecutor); responses.put(md.getName(), future); } Map<String, Exception> exceptions; try { exceptions = awaitCompletion(responses, userExecutor, maxTime, logger, String.format("searching for md5 in container %s", containerName)); } catch (TimeoutException te) { throw propagate(te); } if (exceptions.size() > 0) throw new BlobRuntimeException( String.format("searching for md5 in container %s: %s", containerName, exceptions)); try { return queue.poll(1, TimeUnit.MICROSECONDS) != null; } catch (InterruptedException e) { Throwables.propagate(e); return false; } catch (Exception e) { Throwables.propagateIfPossible(e, BlobRuntimeException.class); throw new BlobRuntimeException( String.format("Error searching for ETAG of value: [%s] in container:%s", value, containerName), e); } }
From source file:dagger.producers.internal.DependencyMethodProducer.java
@Override public final Producer<T> newEntryPointView(final CancellationListener cancellationListener) { return new Producer<T>() { private final Set<ListenableFuture<T>> entryPointFutures = Collections .newSetFromMap(new MapMaker().weakKeys().<ListenableFuture<T>, Boolean>makeMap()); @Override/*from w ww .j a v a 2s . c o m*/ public ListenableFuture<T> get() { final ListenableFuture<T> future = DependencyMethodProducer.this.get(); if (!future.isDone() && entryPointFutures.add(future)) { future.addListener(new Runnable() { @Override public void run() { entryPointFutures.remove(future); if (future.isCancelled()) { // TODO(cgdecker): Make this also propagate the actual value that was passed for // mayInterruptIfRunning cancellationListener.onProducerFutureCancelled(true); } } }, directExecutor()); } return future; } }; }
From source file:io.bitsquare.trade.protocol.trade.tasks.shared.BroadcastAfterLockTime.java
@Override protected void run() { try {/*from w w w .j av a2s . c o m*/ runInterceptHook(); log.debug("ChainHeight/LockTime: {} / {}", processModel.getTradeWalletService().getBestChainHeight(), trade.getLockTimeAsBlockHeight()); if (trade.getLockTimeAsBlockHeight() == 0 || processModel.getTradeWalletService() .getBestChainHeight() >= trade.getLockTimeAsBlockHeight()) { broadcastTx(); } else { ListenableFuture<StoredBlock> blockHeightFuture = processModel.getTradeWalletService() .getBlockHeightFuture(trade.getPayoutTx()); blockHeightFuture.addListener(() -> { try { log.debug("Block height reached " + blockHeightFuture.get().getHeight()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (ExecutionException e) { e.printStackTrace(); } broadcastTx(); }, UserThread::execute); } } catch (Throwable t) { failed(t); } }
From source file:org.javabits.yar.guice.AbstractExecutionStrategy.java
public void execute(final List<Callable<Void>> tasks, final long timeout, final TimeUnit unit) throws InterruptedException { for (int i = 0; i < tasks.size(); i++) { final int taskNumber = i; Callable<Void> task = tasks.get(i); final ListenableFuture<Void> future = executorService().submit(task); pendingTasks.put(future, task);/*from www . j av a2 s.c om*/ future.addListener(new Runnable() { @Override public void run() { pendingTasks.remove(future); } }, executorService()); addCallback(future, new FutureCallback<Void>() { @Override public void onSuccess(Void result) { LOG.log(Level.FINE, String.format("Listener task succeeded : %s", tasks.get(taskNumber))); } @Override public void onFailure(Throwable t) { LOG.log(Level.SEVERE, String.format("Listener task failed: %s", tasks.get(taskNumber)), t); } }); } }
From source file:org.apache.druid.server.QueryManager.java
@Override public void registerQuery(Query query, final ListenableFuture future) { final String id = query.getId(); final List<String> datasources = query.getDataSource().getNames(); queries.put(id, future);/*from w w w. j a v a 2 s. c o m*/ queryDatasources.putAll(id, datasources); future.addListener(new Runnable() { @Override public void run() { queries.remove(id, future); for (String datasource : datasources) { queryDatasources.remove(id, datasource); } } }, MoreExecutors.sameThreadExecutor()); }
From source file:com.google.gerrit.pgm.Reindex.java
private int indexAll() throws Exception { ReviewDb db = sysInjector.getInstance(ReviewDb.class); ChangeIndexer indexer = sysInjector.getInstance(ChangeIndexer.class); Stopwatch sw = new Stopwatch().start(); int queueLen = 2 * threads; final Semaphore sem = new Semaphore(queueLen); final AtomicBoolean ok = new AtomicBoolean(true); int i = 0;//from ww w . j a v a 2s. co m for (final Change change : db.changes().all()) { sem.acquire(); final ListenableFuture<?> future = indexer.index(change); future.addListener(new Runnable() { @Override public void run() { try { future.get(); } catch (InterruptedException e) { log.error("Failed to index change " + change.getId(), e); ok.set(false); } catch (ExecutionException e) { log.error("Failed to index change " + change.getId(), e); ok.set(false); } finally { sem.release(); } } }, MoreExecutors.sameThreadExecutor()); i++; } sem.acquire(queueLen); double elapsed = sw.elapsed(TimeUnit.MILLISECONDS) / 1000d; System.out.format("Reindexed %d changes in %.02fms\n", i, elapsed); return ok.get() ? 0 : 1; }
From source file:org.nmdp.service.epitope.guice.CachingFunction.java
/** * notify listeners about a cache refresh * @param future the future of the async cache refresh * @param key the key of the refresh//www . j a v a 2 s. c om * @param oldValue the old value */ private void notifyListeners(final ListenableFuture<Optional<V>> future, final K key, final Optional<V> oldValue) { for (final CachingFunctionListener<K, V> listener : listenerList) { future.addListener(() -> { try { listener.reloaded(key, oldValue.orNull(), future.get().orNull()); } catch (Exception e) { throw new RuntimeException("caught exception while notifying listener (key: " + key + ", oldValue: " + oldValue + ")"); } }, MoreExecutors.directExecutor()); } }
From source file:com.continuuity.loom.common.zookeeper.lib.ZKCollection.java
private void setExternalChangeWatcher() throws ExecutionException, InterruptedException { ZKOperations.watchChildren(zkClient, "", new ZKOperations.ChildrenCallback() { @Override/*from w w w . j ava2s . co m*/ public void updated(NodeChildren nodeChildren) { List<String> nodes = nodeChildren.getChildren(); List<OperationFuture<NodeData>> dataFutures = Lists.newArrayList(); for (String node : nodes) { dataFutures.add(zkClient.getData(getNodePath(node))); } final ListenableFuture<List<NodeData>> fetchFuture = Futures.successfulAsList(dataFutures); fetchFuture.addListener(new Runnable() { @Override public void run() { ImmutableList.Builder<T> builder = ImmutableList.builder(); // fetchFuture is set by this time List<NodeData> nodesData = Futures.getUnchecked(fetchFuture); for (NodeData nodeData : nodesData) { builder.add(serializer.deserialize(nodeData.getData())); } currentView.set(builder.build()); } }, Threads.SAME_THREAD_EXECUTOR); } }); }