List of usage examples for com.google.common.util.concurrent Futures addCallback
public static <V> void addCallback(ListenableFuture<V> future, FutureCallback<? super V> callback)
From source file:com.amazonaws.services.kinesis.producer.sample.SampleProducer.java
public static void main(String[] args) throws Exception { final KinesisProducer producer = getKinesisProducer(); // The monotonically increasing sequence number we will put in the data of each record final AtomicLong sequenceNumber = new AtomicLong(0); // The number of records that have finished (either successfully put, or failed) final AtomicLong completed = new AtomicLong(0); // KinesisProducer.addUserRecord is asynchronous. A callback can be used to receive the results. final FutureCallback<UserRecordResult> callback = new FutureCallback<UserRecordResult>() { @Override/*from w ww . j ava 2s.c o m*/ public void onFailure(Throwable t) { // We don't expect any failures during this sample. If it // happens, we will log the first one and exit. if (t instanceof UserRecordFailedException) { Attempt last = Iterables.getLast(((UserRecordFailedException) t).getResult().getAttempts()); log.error(String.format("Record failed to put - %s : %s", last.getErrorCode(), last.getErrorMessage())); } log.error("Exception during put", t); System.exit(1); } @Override public void onSuccess(UserRecordResult result) { completed.getAndIncrement(); } }; // The lines within run() are the essence of the KPL API. final Runnable putOneRecord = new Runnable() { @Override public void run() { ByteBuffer data = Utils.generateData(sequenceNumber.get(), DATA_SIZE); // TIMESTAMP is our partition key ListenableFuture<UserRecordResult> f = producer.addUserRecord(STREAM_NAME, TIMESTAMP, Utils.randomExplicitHashKey(), data); Futures.addCallback(f, callback); } }; // This gives us progress updates EXECUTOR.scheduleAtFixedRate(new Runnable() { @Override public void run() { long put = sequenceNumber.get(); long total = RECORDS_PER_SECOND * SECONDS_TO_RUN; double putPercent = 100.0 * put / total; long done = completed.get(); double donePercent = 100.0 * done / total; log.info(String.format("Put %d of %d so far (%.2f %%), %d have completed (%.2f %%)", put, total, putPercent, done, donePercent)); } }, 1, 1, TimeUnit.SECONDS); // Kick off the puts log.info(String.format("Starting puts... will run for %d seconds at %d records per second", SECONDS_TO_RUN, RECORDS_PER_SECOND)); executeAtTargetRate(EXECUTOR, putOneRecord, sequenceNumber, SECONDS_TO_RUN, RECORDS_PER_SECOND); // Wait for puts to finish. After this statement returns, we have // finished all calls to putRecord, but the records may still be // in-flight. We will additionally wait for all records to actually // finish later. EXECUTOR.awaitTermination(SECONDS_TO_RUN + 1, TimeUnit.SECONDS); // If you need to shutdown your application, call flushSync() first to // send any buffered records. This method will block until all records // have finished (either success or fail). There are also asynchronous // flush methods available. // // Records are also automatically flushed by the KPL after a while based // on the time limit set with Configuration.setRecordMaxBufferedTime() log.info("Waiting for remaining puts to finish..."); producer.flushSync(); log.info("All records complete."); // This kills the child process and shuts down the threads managing it. producer.destroy(); log.info("Finished."); }
From source file:com.yahoo.yqlplus.engine.internal.java.runtime.PropagateFuture.java
public static <V> void propagate(ListenableFuture<? extends V> source, SettableFuture<V> target) { Futures.addCallback(source, new PropagateFuture<V>(target)); }
From source file:io.v.util.Util.java
static <T> void asCallback(ListenableFuture<T> future, final Callback<T> callback) { Futures.addCallback(future, new FutureCallback<T>() { @Override// w ww. j a va2s .c o m public void onSuccess(T result) { callback.onSuccess(result); } @Override public void onFailure(Throwable t) { callback.onFailure(t instanceof VException ? (VException) t : new VException(t.getMessage())); } }); }
From source file:io.v.rx.RxInputChannel.java
private static <T> void connect(final InputChannel<T> i, final Subscriber<? super T> s) { Futures.addCallback(i.recv(), new FutureCallback<T>() { @Override//from w w w . ja v a2s.c o m public void onSuccess(T result) { s.onNext(result); connect(i, s); } @Override public void onFailure(Throwable t) { if (t instanceof EndOfFileException) { s.onCompleted(); } else { s.onError(t); } } }); }
From source file:io.baku.examples.distro.RxInputChannel.java
private static <T> void connect(final InputChannel<T> i, final Subscriber<? super T> s) { Futures.addCallback(i.recv(), new FutureCallback<T>() { @Override//from w ww . j a va 2 s . c o m public void onSuccess(final T r) { s.onNext(r); connect(i, s); } @Override public void onFailure(final Throwable t) { if (t instanceof EndOfFileException) { s.onCompleted(); } else { s.onError(t); } } }); }
From source file:com.google.gapid.server.Tracer.java
public static Trace trace(Display display, TraceRequest request, Listener listener) { GapitTraceProcess process = new GapitTraceProcess(request, message -> display.asyncExec(() -> listener.onProgress(message))); Futures.addCallback(process.start(), new FutureCallback<Boolean>() { @Override/*from w ww . ja v a2s . c om*/ public void onFailure(Throwable t) { // Give some time for all the output to pump through. display.asyncExec(() -> display.timerExec(500, () -> listener.onFailure(t))); } @Override public void onSuccess(Boolean result) { // Ignore. } }); return new Trace() { @Override public void stop() { process.stopTracing(); } }; }
From source file:global.PlayAsync.java
public static <T, A> Future<F.Tuple<T, A>> asFuture(ListenableFuture<T> future, A a) { final scala.concurrent.Promise<F.Tuple<T, A>> promise = new DefaultPromise<F.Tuple<T, A>>(); Futures.addCallback(future, new FutureCallback<T>() { @Override/*from w ww. j a v a 2s .c o m*/ public void onSuccess(T result) { promise.success(new F.Tuple<T, A>(result, a)); } @Override public void onFailure(Throwable t) { promise.failure(t); } }); return promise.future(); }
From source file:com.spotify.apollo.concurrent.Util.java
public static <T> CompletionStage<T> asStage(ListenableFuture<T> future) { CompletableFuture<T> completableFuture = new CompletableFuture<>(); Futures.addCallback(future, new FutureCallback<T>() { @Override//from w ww.j av a 2 s. c o m public void onSuccess(T result) { completableFuture.complete(result); } @Override public void onFailure(Throwable t) { completableFuture.completeExceptionally(t); } }); return completableFuture; }
From source file:com.vmware.photon.controller.common.zookeeper.ServiceNodeUtils.java
public static void joinService(final ServiceNode serviceNode, final long retryIntervalMsec, final ServiceNodeEventHandler serviceNodeEventHandler) { Futures.addCallback(serviceNode.join(), new FutureCallback<ServiceNode.Lease>() { @Override//ww w . j a v a2 s .co m public void onSuccess(ServiceNode.Lease result) { if (serviceNodeEventHandler != null) { serviceNodeEventHandler.onJoin(); } handleLeaseExpiration(result, serviceNode, retryIntervalMsec, serviceNodeEventHandler); } @Override public void onFailure(Throwable t) { // This could happen when connection to ZK goes away while we were trying to join the service. // The proper way to proceed seems to be to just try to join again, rather than exit the process. logger.error("Could not acquire service lease", t); logger.debug("Sleeping for {} before retrying", retryIntervalMsec); try { Thread.sleep(retryIntervalMsec); } catch (InterruptedException e) { logger.error("Failed to sleep between registration retries", e); } joinService(serviceNode, retryIntervalMsec, serviceNodeEventHandler); } }); }
From source file:com.spotify.heroic.metric.datastax.Async.java
/** * Helper method to convert a {@link ListenableFuture} to an {@link AsyncFuture}. *///from ww w.ja va2 s.co m public static <T> AsyncFuture<T> bind(AsyncFramework async, ListenableFuture<T> source) { final ResolvableFuture<T> target = async.future(); Futures.addCallback(source, new FutureCallback<T>() { @Override public void onSuccess(T result) { target.resolve(result); } @Override public void onFailure(Throwable t) { target.fail(t); } }); target.onCancelled(() -> { source.cancel(false); }); return target; }