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

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

Introduction

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

Prototype

@Override
    public void addListener(Runnable listener, Executor exec) 

Source Link

Usage

From source file:org.fcrepo.indexer.AsynchIndexer.java

@Override
public ListenableFuture<Result> remove(final URI identifier) throws IOException {
    LOGGER.debug("Received remove for identifier: {}", identifier);
    final ListenableFutureTask<Result> task = ListenableFutureTask.create(removeSynch(identifier));
    task.addListener(new Runnable() {
        @Override/*www . j  a v a 2  s  .  co m*/
        public void run() {
            synchronized (this) {
                notifyAll();
            }
        }
    }, executorService());
    executorService().submit(task);
    return task;
}

From source file:org.fcrepo.indexer.AsynchIndexer.java

@Override
public ListenableFuture<Result> update(final URI identifier, final Content content) throws IOException {
    LOGGER.debug("Received update for identifier: {}", identifier);

    final ListenableFutureTask<Result> task = ListenableFutureTask.create(updateSynch(identifier, content));
    task.addListener(new Runnable() {
        @Override//from www .  ja  v  a2 s  .  c  o  m
        public void run() {
            synchronized (this) {
                notifyAll();
            }
        }
    }, executorService());
    executorService().submit(task);
    LOGGER.debug("Issued task to execution pool for identifier: {}", identifier);
    return task;
}

From source file:com.linkedin.pinot.core.query.scheduler.PriorityScheduler.java

@Override
public void start() {
    super.start();
    scheduler = new Thread(new Runnable() {
        @Override/*  w  w w .j  av a2s .  co  m*/
        public void run() {
            while (isRunning) {
                try {
                    runningQueriesSemaphore.acquire();
                } catch (InterruptedException e) {
                    if (!isRunning) {
                        LOGGER.info("Shutting down scheduler");
                    } else {
                        LOGGER.error("Interrupt while acquiring semaphore. Exiting.", e);
                    }
                    break;
                }
                try {
                    final SchedulerQueryContext request = queryQueue.take();
                    if (request == null) {
                        continue;
                    }
                    ServerQueryRequest queryRequest = request.getQueryRequest();
                    final QueryExecutorService executor = resourceManager.getExecutorService(queryRequest,
                            request.getSchedulerGroup());
                    final ListenableFutureTask<byte[]> queryFutureTask = createQueryFutureTask(queryRequest,
                            executor);
                    queryFutureTask.addListener(new Runnable() {
                        @Override
                        public void run() {
                            executor.releaseWorkers();
                            request.getSchedulerGroup().endQuery();
                            runningQueriesSemaphore.release();
                            checkStopResourceManager();
                            if (!isRunning && runningQueriesSemaphore.availablePermits() == numRunners) {
                                resourceManager.stop();
                            }
                        }
                    }, MoreExecutors.directExecutor());
                    request.setResultFuture(queryFutureTask);
                    request.getSchedulerGroup().startQuery();
                    queryRequest.getTimerContext().getPhaseTimer(ServerQueryPhase.SCHEDULER_WAIT)
                            .stopAndRecord();
                    resourceManager.getQueryRunners().submit(queryFutureTask);
                } catch (Throwable t) {
                    LOGGER.error(
                            "Error in scheduler thread. This is indicative of a bug. Please report this. Server will continue with errors",
                            t);
                }
            }
            if (isRunning) {
                throw new RuntimeException(
                        "FATAL: Scheduler thread is quitting.....something went horribly wrong.....!!!");
            } else {
                failAllPendingQueries();
            }
        }
    });
    scheduler.setName("scheduler");
    scheduler.setPriority(Thread.MAX_PRIORITY);
    scheduler.setDaemon(true);
    scheduler.start();
}

From source file:org.fcrepo.indexer.sparql.SparqlIndexer.java

private Callable<Void> exec(final UpdateRequest update, final boolean blocking) {
    if (update.getOperations().isEmpty()) {
        LOGGER.debug("Received empty update/remove operation.");
        return new Callable<Void>() {

            @Override/* w ww. j a v a 2  s .  c o m*/
            public Void call() {
                return null;
            }
        };
    }

    final Callable<Void> callable = new Callable<Void>() {

        @Override
        public Void call() {

            if (formUpdates) {
                // form updates
                final UpdateProcessor proc = createRemoteForm(update, updateBase);
                proc.execute();
            } else {
                // normal SPARQL updates
                final UpdateProcessRemote proc = new UpdateProcessRemote(update, updateBase, emptyContext);
                try {
                    proc.execute();
                } catch (final Exception e) {
                    LOGGER.error("Error executing Sparql update/remove!", e);
                }
            }
            return null;
        }
    };

    if (blocking) {
        try {
            callable.call();
        } catch (Exception e) {
            LOGGER.error("Error calling Sparql update/remove!, {}", e.getMessage());
        }

    } else {
        final ListenableFutureTask<Void> task = ListenableFutureTask.create(callable);
        task.addListener(new Runnable() {

            @Override
            public void run() {
                LOGGER.debug("Completed Sparql update/removal.");
                if (LOGGER.isTraceEnabled()) {
                    try (final OutputStream buffer = new ByteArrayOutputStream()) {
                        final IndentedWriter out = new IndentedWriter(buffer);
                        update.output(out);
                        LOGGER.trace("Executed update/remove operation:\n{}", buffer.toString());
                        out.close();
                    } catch (final IOException e) {
                        LOGGER.error("Couldn't retrieve execution of update/remove operation!", e);
                    }
                }
            }
        }, executorService);
        executorService.submit(task);
    }

    return callable;
}

From source file:com.twitter.common.net.UrlResolver.java

public Future<ResolvedUrl> resolveUrlAsync(final String url, final ResolvedUrlHandler handler) {
    Preconditions.checkNotNull("Asynchronous URL resolution cannot be performed without a valid handler.",
            handler);/*  www. ja v  a 2  s. c  om*/

    try {
        poolEntrySemaphore.acquire();
    } catch (InterruptedException e) {
        LOG.log(Level.SEVERE, "Interrupted while waiting for thread to resolve URL: " + url, e);
        return null;
    }
    final ListenableFutureTask<ResolvedUrl> future = ListenableFutureTask.create(new Callable<ResolvedUrl>() {
        @Override
        public ResolvedUrl call() {
            return resolveUrl(url);
        }
    });

    future.addListener(new Runnable() {
        @Override
        public void run() {
            try {
                handler.resolved(future);
            } finally {
                poolEntrySemaphore.release();
            }
        }
    }, handlerExecutor);

    executor.execute(future);
    return future;
}

From source file:org.voltdb.ClientInterface.java

public ListenableFutureTask<?> processFinishedCompilerWork(final AsyncCompilerResult result) {
    /*/*from  w w w  .  j a  v  a 2s  . com*/
     * Do the task in the network thread associated with the connection
     * so that access to the CIHM can be lock free for fast path work.
     * Can't access the CIHM from this thread without adding locking.
     */
    final Connection c = (Connection) result.clientData;
    final ListenableFutureTask<?> ft = ListenableFutureTask.create(new Runnable() {
        @Override
        public void run() {
            if (result.errorMsg == null) {
                if (result instanceof AdHocPlannedStmtBatch) {
                    final AdHocPlannedStmtBatch plannedStmtBatch = (AdHocPlannedStmtBatch) result;
                    // assume all stmts have the same catalog version
                    if ((plannedStmtBatch.getPlannedStatementCount() > 0) && (plannedStmtBatch
                            .getPlannedStatement(0).catalogVersion != m_catalogContext.get().catalogVersion)) {

                        /* The adhoc planner learns of catalog updates after the EE and the
                           rest of the system. If the adhoc sql was planned against an
                           obsolete catalog, re-plan. */
                        LocalObjectMessage work = new LocalObjectMessage(new AdHocPlannerWork(m_siteId, false,
                                plannedStmtBatch.clientHandle, plannedStmtBatch.connectionId,
                                plannedStmtBatch.hostname, plannedStmtBatch.adminConnection,
                                plannedStmtBatch.clientData, plannedStmtBatch.sqlBatchText,
                                plannedStmtBatch.getSQLStatements(), plannedStmtBatch.partitionParam, null,
                                false, true, m_adhocCompletionHandler));

                        m_mailbox.send(m_plannerSiteId, work);
                    } else {
                        createAdHocTransaction(plannedStmtBatch);
                    }
                } else if (result instanceof CatalogChangeResult) {
                    final CatalogChangeResult changeResult = (CatalogChangeResult) result;
                    // create the execution site task
                    StoredProcedureInvocation task = new StoredProcedureInvocation();
                    task.procName = "@UpdateApplicationCatalog";
                    task.setParams(changeResult.encodedDiffCommands, changeResult.catalogBytes,
                            changeResult.expectedCatalogVersion, changeResult.deploymentString,
                            changeResult.deploymentCRC);
                    task.clientHandle = changeResult.clientHandle;

                    /*
                     * Round trip the invocation to initialize it for command logging
                     */
                    FastSerializer fs = new FastSerializer();
                    try {
                        fs.writeObject(task);
                        ByteBuffer source = fs.getBuffer();
                        ByteBuffer copy = ByteBuffer.allocate(source.remaining());
                        copy.put(source);
                        copy.flip();
                        FastDeserializer fds = new FastDeserializer(copy);
                        task = new StoredProcedureInvocation();
                        task.readExternal(fds);
                    } catch (Exception e) {
                        hostLog.fatal(e);
                        VoltDB.crashLocalVoltDB(e.getMessage(), true, e);
                    }

                    // initiate the transaction. These hard-coded values from catalog
                    // procedure are horrible, horrible, horrible.
                    createTransaction(changeResult.connectionId, changeResult.hostname,
                            changeResult.adminConnection, task, false, true, true, m_allPartitions,
                            m_allPartitions.length, changeResult.clientData, 0, EstTime.currentTimeMillis(),
                            false);
                } else {
                    throw new RuntimeException(
                            "Should not be able to get here (ClientInterface.checkForFinishedCompilerWork())");
                }
            } else {
                ClientResponseImpl errorResponse = new ClientResponseImpl(ClientResponseImpl.UNEXPECTED_FAILURE,
                        new VoltTable[0], result.errorMsg, result.clientHandle);
                ByteBuffer buf = ByteBuffer.allocate(errorResponse.getSerializedSize() + 4);
                buf.putInt(buf.capacity() - 4);
                errorResponse.flattenToBuffer(buf);
                buf.flip();
                c.writeStream().enqueue(buf);
            }
        }
    }, null);
    if (c != null) {
        c.queueTask(ft);
    }

    /*
     * Add error handling in case of an unexpected exception
     */
    ft.addListener(new Runnable() {
        @Override
        public void run() {
            try {
                ft.get();
            } catch (Exception e) {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                e.printStackTrace(pw);
                pw.flush();
                ClientResponseImpl errorResponse = new ClientResponseImpl(ClientResponseImpl.UNEXPECTED_FAILURE,
                        new VoltTable[0], result.errorMsg, result.clientHandle);
                ByteBuffer buf = ByteBuffer.allocate(errorResponse.getSerializedSize() + 4);
                buf.putInt(buf.capacity() - 4);
                errorResponse.flattenToBuffer(buf);
                buf.flip();
                c.writeStream().enqueue(buf);
            }
        }
    }, MoreExecutors.sameThreadExecutor());

    //Return the future task for test code
    return ft;
}