Example usage for com.google.common.util.concurrent ListenableFuture addListener

List of usage examples for com.google.common.util.concurrent ListenableFuture addListener

Introduction

In this page you can find the example usage for com.google.common.util.concurrent ListenableFuture addListener.

Prototype

void addListener(Runnable listener, Executor executor);

Source Link

Document

Registers a listener to be Executor#execute(Runnable) run on the given executor.

Usage

From source file:io.prestosql.operator.DriverContext.java

public void recordBlocked(ListenableFuture<?> blocked) {
    requireNonNull(blocked, "blocked is null");

    BlockedMonitor monitor = new BlockedMonitor();

    BlockedMonitor oldMonitor = blockedMonitor.getAndSet(monitor);
    if (oldMonitor != null) {
        oldMonitor.run();/*from  w w w.ja v a  2  s  . co  m*/
    }

    blocked.addListener(monitor, notificationExecutor);
}

From source file:org.copperengine.core.persistent.hybrid.HybridDBStorage.java

private void handleEarlyResponse(final Response<?> response, final Acknowledge ack) throws Exception {
    synchronized (currentlyProcessingEarlyResponses) {
        currentlyProcessingEarlyResponses.add(response.getCorrelationId());
    }//from   www.j  a va 2  s. c o  m
    final ListenableFuture<Void> future = storage.safeEarlyResponse(response.getCorrelationId(),
            serializer.serializeResponse(response));
    future.addListener(new Runnable() {
        @Override
        public void run() {
            try {
                future.get();
                ack.onSuccess();
            } catch (Exception e) {
                logger.error("safeEarlyResponse failed", e);
                ack.onException(e);
            } finally {
                synchronized (currentlyProcessingEarlyResponses) {
                    currentlyProcessingEarlyResponses.remove(response.getCorrelationId());
                    currentlyProcessingEarlyResponses.notifyAll();
                }
            }
        }
    }, executor);
}

From source file:org.apache.twill.discovery.ZKDiscoveryService.java

/**
 * Creates a CacheLoader for creating live Iterable for watching instances changes for a given service.
 */// w  w w . j av  a  2s .  c  o m
private CacheLoader<String, ServiceDiscoveredCacheEntry> createServiceLoader() {
    return new CacheLoader<String, ServiceDiscoveredCacheEntry>() {
        @Override
        public ServiceDiscoveredCacheEntry load(String service) throws Exception {
            final DefaultServiceDiscovered serviceDiscovered = new DefaultServiceDiscovered(service);
            final String pathBase = "/" + service;

            // Watch for children changes in /service
            Cancellable cancellable = ZKOperations.watchChildren(zkClient, pathBase,
                    new ZKOperations.ChildrenCallback() {
                        @Override
                        public void updated(NodeChildren nodeChildren) {
                            // Fetch data of all children nodes in parallel.
                            List<String> children = nodeChildren.getChildren();
                            List<OperationFuture<NodeData>> dataFutures = Lists
                                    .newArrayListWithCapacity(children.size());
                            for (String child : children) {
                                dataFutures.add(zkClient.getData(pathBase + "/" + child));
                            }

                            // Update the service map when all fetching are done.
                            final ListenableFuture<List<NodeData>> fetchFuture = Futures
                                    .successfulAsList(dataFutures);
                            fetchFuture.addListener(new Runnable() {
                                @Override
                                public void run() {
                                    ImmutableSet.Builder<Discoverable> builder = ImmutableSet.builder();
                                    for (NodeData nodeData : Futures.getUnchecked(fetchFuture)) {
                                        // For successful fetch, decode the content.
                                        if (nodeData != null) {
                                            Discoverable discoverable = DiscoverableAdapter
                                                    .decode(nodeData.getData());
                                            if (discoverable != null) {
                                                builder.add(discoverable);
                                            }
                                        }
                                    }
                                    serviceDiscovered.setDiscoverables(builder.build());
                                }
                            }, Threads.SAME_THREAD_EXECUTOR);
                        }
                    });
            return new ServiceDiscoveredCacheEntry(serviceDiscovered, cancellable);
        }
    };
}

From source file:org.apache.abdera2.common.protocol.Session.java

/**
 * Processes requests asynchronously.. the listener will
 * be invoked once the call completes/*from  ww w. j a  va  2 s. c  o  m*/
 */
public <X extends ClientResponse> void process(ExecutorService executor, Callable<X> resp,
        final Listener<X> listener) {
    ListeningExecutorService exec = MoreExecutors.listeningDecorator(executor);
    final ListenableFuture<X> lf = exec.submit(resp);
    lf.addListener(new Runnable() {
        public void run() {
            X resp = null;
            try {
                resp = lf.get();
                listener.onResponse(resp);
            } catch (Throwable t) {
                throw ExceptionHelper.propogate(t);
            } finally { // auto release since by this point we know we're done with it
                if (resp != null)
                    resp.release();
            }
        }
    }, executor);
}

From source file:com.afewmoreamps.JitCaskImpl.java

@Override
public ListenableFuture<RemoveResult> remove(final byte[] key, final boolean waitForSync) {
    if (key == null) {
        throw new IllegalArgumentException();
    }//w  ww  . ja va 2 s  .co  m

    final long start = System.currentTimeMillis();

    try {
        m_maxOutstandingWrites.acquire();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }

    final SettableFuture<RemoveResult> retval = SettableFuture.create();
    retval.addListener(new Runnable() {
        @Override
        public void run() {
            m_maxOutstandingWrites.release();
        }
    }, MoreExecutors.sameThreadExecutor());

    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException e) {
        retval.setException(e);
        return retval;
    }

    final byte keyHash[] = md.digest(key);

    m_writeThread.execute(new Runnable() {
        @Override
        public void run() {
            KDEntry entry = m_keyDir.get(KeyDir.decorateKeyHash(keyHash));
            if (entry == null) {
                retval.set(new RemoveResult((int) (System.currentTimeMillis() - start)));
                return;
            }
            final MiniCask mc = m_miniCasks.get(entry.fileId);
            try {
                putImpl(MiniCask.constructTombstoneEntry(keyHash, entry.fileId, mc.m_timestamp), keyHash, true);
            } catch (Throwable t) {
                retval.setException(t);
                return;
            }
            if (waitForSync) {
                final ListenableFuture<Long> syncTask = m_nextSyncTask;
                syncTask.addListener(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            retval.set(new RemoveResult((int) (syncTask.get() - start)));
                        } catch (Throwable t) {
                            retval.setException(t);
                            return;
                        }
                    }
                }, MoreExecutors.sameThreadExecutor());
            } else {
                retval.set(new RemoveResult((int) (System.currentTimeMillis() - start)));
            }
        }
    });
    return retval;
}

From source file:com.skcraft.launcher.dialog.LauncherFrame.java

private void launch(Instance instance, Session session) {
    final File extractDir = launcher.createExtractDir();

    // Get the process
    Runner task = new Runner(launcher, instance, session, extractDir);
    ObservableFuture<Process> processFuture = new ObservableFuture<Process>(launcher.getExecutor().submit(task),
            task);/*from w  ww  . jav  a  2 s .  c  o  m*/

    // Show process for the process retrieval
    ProgressDialog.showProgress(this, processFuture, _("launcher.launchingTItle"),
            _("launcher.launchingStatus", instance.getTitle()));

    // If the process is started, get rid of this window
    Futures.addCallback(processFuture, new FutureCallback<Process>() {
        @Override
        public void onSuccess(Process result) {
            dispose();
        }

        @Override
        public void onFailure(Throwable t) {
        }
    });

    // Watch the created process
    ListenableFuture<?> future = Futures.transform(processFuture, new LaunchProcessHandler(launcher),
            launcher.getExecutor());
    SwingHelper.addErrorDialogCallback(null, future);

    // Clean up at the very end
    future.addListener(new Runnable() {
        @Override
        public void run() {
            try {
                log.info("Process ended; cleaning up " + extractDir.getAbsolutePath());
                FileUtils.deleteDirectory(extractDir);
            } catch (IOException e) {
                log.log(Level.WARNING, "Failed to clean up " + extractDir.getAbsolutePath(), e);
            }
            instancesModel.update();
        }
    }, sameThreadExecutor());
}

From source file:com.facebook.buck.rules.UnskippedRulesTracker.java

public ListenableFuture<Void> markRuleAsUsed(final BuildRule rule, final BuckEventBus eventBus) {
    // Add a reference to the used rule so that it is never marked as skipped.
    ListenableFuture<Void> future = acquireReference(rule);

    if (rule instanceof HasRuntimeDeps) {
        // Add references to rule's runtime deps since they cannot be skipped now.
        future = MoreFutures.chainExceptions(future,
                acquireReferences(ruleFinder.filterBuildRuleInputs(((HasRuntimeDeps) rule).getRuntimeDeps())));
    }//from w  w  w.j  a  v  a 2  s.  c  o  m

    // Release references from rule's dependencies since this rule will not need them anymore.
    future = Futures.transformAsync(future,
            input -> Futures.transformAsync(ruleDepsCache.get(rule), releaseReferences, executor));

    future.addListener(() -> sendEventIfStateChanged(eventBus), MoreExecutors.directExecutor());

    return future;
}

From source file:com.continuuity.weave.internal.ZKServiceDecorator.java

@Override
protected void doStart() {
    callbackExecutor = Executors.newSingleThreadExecutor(Threads.createDaemonThreadFactory("message-callback"));
    Futures.addCallback(createLiveNode(), new FutureCallback<String>() {
        @Override/*from  w w w  . j a v a  2  s.c o  m*/
        public void onSuccess(String result) {
            // Create nodes for states and messaging
            StateNode stateNode = new StateNode(ServiceController.State.STARTING);

            final ListenableFuture<List<String>> createFuture = Futures.allAsList(
                    deleteAndCreate(getZKPath("messages"), null, CreateMode.PERSISTENT),
                    deleteAndCreate(getZKPath("state"), encodeStateNode(stateNode), CreateMode.PERSISTENT));

            createFuture.addListener(new Runnable() {
                @Override
                public void run() {
                    try {
                        createFuture.get();
                        // Starts the decorated service
                        decoratedService.addListener(createListener(), Threads.SAME_THREAD_EXECUTOR);
                        decoratedService.start();
                    } catch (Exception e) {
                        notifyFailed(e);
                    }
                }
            }, Threads.SAME_THREAD_EXECUTOR);
        }

        @Override
        public void onFailure(Throwable t) {
            notifyFailed(t);
        }
    });
}

From source file:com.afewmoreamps.JitCaskImpl.java

@Override
public ListenableFuture<PutResult> put(final byte[] key, final byte[] value, final boolean waitForSync) {
    if (key == null || value == null) {
        throw new IllegalArgumentException();
    }// ww  w  .  j a  v  a2  s.  c om

    final int uncompressedSize = key.length + value.length + MiniCask.HEADER_SIZE + 8;//8 is the length prefixes in the compressed entry for the key and value
    /*
     * Record when the put started
     */
    final long start = System.currentTimeMillis();

    /*
     * This is the return value that will be set with the result
     * or any exceptions thrown during the put
     */
    final SettableFuture<PutResult> retval = SettableFuture.create();

    /*
     * If compression is requested, attempt to compress the value
     * and generate the CRC in a separate thread pool before submitting
     * to the single write thread. This allows parallelism for what is potentially
     * the more CPU intensive part of a write. Can't have more write
     * threads so best to scale out as far as possible before giving it work.
     */
    final ListenableFuture<Object[]> assembledEntryFuture = m_compressionThreads
            .submit(new Callable<Object[]>() {
                @Override
                public Object[] call() throws Exception {
                    return MiniCask.constructEntry(key, value);
                }
            });

    /*
     * Limit the maximum number of outstanding writes
     * to avoid OOM in naive benchmarks/applications
     */
    try {
        m_maxOutstandingWrites.acquire();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
    retval.addListener(new Runnable() {
        @Override
        public void run() {
            m_maxOutstandingWrites.release();
        }
    }, MoreExecutors.sameThreadExecutor());

    /*
     * Submit the write to the single write thread
     * which will write the kv pair to the current file and
     * upsert it into the keydir. If sync was not requested
     * then the retval future will be set as soon as the write
     * thread writes the new kv pair to the memory mapped file (page cache).
     * Otherwise it adds a listener to the next sync task that will set the value
     * once sync has been performed.
     */
    m_writeThread.execute(new Runnable() {
        @Override
        public void run() {
            /*
             * Retrieve the compression results, forwarding any exceptions
             * to the retval future.
             */
            Object assembledEntry[];
            try {
                assembledEntry = assembledEntryFuture.get();
            } catch (Throwable t) {
                retval.setException(t);
                return;
            }

            final byte entryBytes[] = (byte[]) assembledEntry[0];
            final byte keyHash[] = (byte[]) assembledEntry[1];

            try {
                putImpl(entryBytes, keyHash, false);
            } catch (Throwable t) {
                retval.setException(t);
                return;
            }

            /*
             * If the put requested waiting for sync then don't set the retval future
             * immediately. Add a listener for the next sync task that will do it
             * once the data is really durable.
             *
             * Otherwise set it immediately and use the current time to reflect the latency
             * of the put
             */
            if (waitForSync) {
                final ListenableFuture<Long> syncTask = m_nextSyncTask;
                syncTask.addListener(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            retval.set(new PutResult(uncompressedSize, entryBytes.length,
                                    (int) (syncTask.get() - start)));
                        } catch (Throwable t) {
                            retval.setException(t);
                            return;
                        }
                    }
                }, MoreExecutors.sameThreadExecutor());
            } else {
                retval.set(new PutResult(uncompressedSize, entryBytes.length,
                        (int) (System.currentTimeMillis() - start)));
            }
        }
    });

    return retval;
}

From source file:org.dcache.xrootd.pool.XrootdPoolRequestHandler.java

/**
 * Lookup the file descriptor and invoke its close operation.
 *
 * @param ctx received from the netty pipeline
 * @param msg The actual request/* w  ww. ja  v  a  2 s.  c  o  m*/
 */
@Override
protected XrootdResponse<CloseRequest> doOnClose(ChannelHandlerContext ctx, CloseRequest msg)
        throws XrootdException {
    int fd = msg.getFileHandle();

    if (!isValidFileDescriptor(fd)) {
        _log.warn("Could not find file descriptor for handle {}", fd);
        throw new XrootdException(kXR_FileNotOpen, "The file descriptor does not refer to an " + "open file.");
    }

    ListenableFuture<Void> future = _descriptors.get(fd).getChannel().release();
    future.addListener(() -> {
        try {
            Uninterruptibles.getUninterruptibly(future);
            respond(ctx, withOk(msg));
        } catch (ExecutionException e) {
            Throwable cause = e.getCause();
            if (cause instanceof FileCorruptedCacheException) {
                respond(ctx, withError(msg, kXR_ChkSumErr, cause.getMessage()));
            } else if (cause instanceof CacheException) {
                respond(ctx, withError(msg, kXR_ServerError, cause.getMessage()));
            } else if (cause instanceof IOException) {
                respond(ctx, withError(msg, kXR_IOError, cause.getMessage()));
            } else {
                respond(ctx, withError(msg, kXR_ServerError, cause.toString()));
            }
        } finally {
            _descriptors.set(fd, null);
        }
    }, MoreExecutors.directExecutor());

    return null;
}