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

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

Introduction

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

Prototype

public static <V> ListenableFutureTask<V> create(Runnable runnable, @Nullable V result) 

Source Link

Document

Creates a ListenableFutureTask that will upon running, execute the given Runnable , and arrange that get will return the given result on successful completion.

Usage

From source file:gobblin.util.executors.MDCPropagatingScheduledExecutorService.java

@Override
public ListenableScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
    ListenableFutureTask<Void> task = ListenableFutureTask.create(new MDCPropagatingRunnable(command), null);
    ScheduledFuture<?> scheduled = executorService.schedule(task, delay, unit);
    return new ListenableScheduledTask<>(task, scheduled);
}

From source file:ch.raffael.util.swing.SwingUtil.java

public static ListenableFuture<Void> invokeInEventQueue(Runnable runnable) {
    if (SwingUtilities.isEventDispatchThread()) {
        return Futures.immediateFuture(null);
    } else {//w  ww. ja  v  a  2s  .  c  o m
        ListenableFutureTask<Void> future = ListenableFutureTask.create(runnable, null);
        SwingUtilities.invokeLater(future);
        return future;
    }
}

From source file:io.druid.query.PrioritizedExecutorService.java

@Override
protected <T> PrioritizedListenableFutureTask<T> newTaskFor(Runnable runnable, T value) {
    Preconditions.checkArgument(allowRegularTasks || runnable instanceof PrioritizedRunnable,
            "task does not implement PrioritizedRunnable");
    return PrioritizedListenableFutureTask.create(ListenableFutureTask.create(runnable, value),
            runnable instanceof PrioritizedRunnable ? ((PrioritizedRunnable) runnable).getPriority()
                    : defaultPriority);/*from  w w  w .j  a  va 2  s  .  c  om*/
}

From source file:org.apache.druid.query.PrioritizedExecutorService.java

@Override
protected <T> PrioritizedListenableFutureTask<T> newTaskFor(Runnable runnable, T value) {
    Preconditions.checkArgument(allowRegularTasks || runnable instanceof PrioritizedRunnable,
            "task does not implement PrioritizedRunnable");
    return PrioritizedListenableFutureTask.create(ListenableFutureTask.create(runnable, value),
            runnable instanceof PrioritizedRunnable ? ((PrioritizedRunnable) runnable).getPriority()
                    : defaultPriority,/*w w w  .  j  a  v  a 2 s  .  c o m*/
            config.isFifo() ? queuePosition.decrementAndGet() : 0);
}

From source file:com.yahoo.yqlplus.engine.internal.scope.ScopedTracingExecutor.java

@Override
protected final <T> ListenableFutureTask<T> newTaskFor(Runnable runnable, T value) {
    return ListenableFutureTask.create(runnable, value);
}

From source file:org.apache.fluo.core.impl.SharedBatchWriter.java

ListenableFuture<Void> writeMutationsAsyncFuture(Collection<Mutation> ml) {
    if (ml.size() == 0) {
        return Futures.immediateFuture(null);
    }//  ww  w .ja va2s  .  c  o  m

    ListenableFutureTask<Void> lf = ListenableFutureTask.create(DO_NOTHING, null);
    try {
        MutationBatch mb = new MutationBatch(ml, lf);
        mutQueue.put(mb);
        return lf;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.trinity.foundation.render.qt.impl.painter.PainterImpl.java

@Override
public ListenableFuture<Void> bindView() {

    final QWidget view = this.viewDiscovery.lookupView(this.model);
    final Runnable viewBindingRoutine = new Runnable() {
        @Override/*from w  w w  .  ja  v a2s  .  c om*/
        public void run() {
            final QObject eventTracker = PainterImpl.this.eventTrackerFactory
                    .createQJEventTracker(PainterImpl.this.model, view);
            view.installEventFilter(eventTracker);
            PainterImpl.this.binder.bind(PainterImpl.this.modelExecutor, PainterImpl.this.model, view);

        }
    };
    final ListenableFutureTask<Void> bindViewFuture = ListenableFutureTask.create(viewBindingRoutine, null);
    QApplication.invokeLater(viewBindingRoutine);
    return bindViewFuture;
}

From source file:org.apache.cassandra.db.compaction.CompactionManager.java

public ListenableFuture<?> submitAntiCompaction(final ColumnFamilyStore cfs,
        final Collection<Range<Token>> ranges, final Refs<SSTableReader> sstables, final long repairedAt) {
    Runnable runnable = new WrappedRunnable() {
        @Override//from w  w w.  ja v  a2  s  . c o  m
        @SuppressWarnings("resource")
        public void runMayThrow() throws Exception {
            LifecycleTransaction modifier = null;
            while (modifier == null) {
                for (SSTableReader compactingSSTable : cfs.getTracker().getCompacting())
                    sstables.releaseIfHolds(compactingSSTable);
                Set<SSTableReader> compactedSSTables = new HashSet<>();
                for (SSTableReader sstable : sstables)
                    if (sstable.isMarkedCompacted())
                        compactedSSTables.add(sstable);
                sstables.release(compactedSSTables);
                modifier = cfs.getTracker().tryModify(sstables, OperationType.ANTICOMPACTION);
            }
            performAnticompaction(cfs, ranges, sstables, modifier, repairedAt);
        }
    };
    if (executor.isShutdown()) {
        logger.info("Compaction executor has shut down, not submitting anticompaction");
        sstables.release();
        return Futures.immediateCancelledFuture();
    }

    ListenableFutureTask<?> task = ListenableFutureTask.create(runnable, null);
    executor.submit(task);
    return task;
}

From source file:blusunrize.immersiveengineering.api.ApiUtils.java

public static void addFutureServerTask(World world, Runnable task) {
    if (world.getMinecraftServer() != null)
        synchronized (world.getMinecraftServer().futureTaskQueue) {
            world.getMinecraftServer().futureTaskQueue.add(ListenableFutureTask.create(task, null));
        }/*w w w . ja  va 2s. c o m*/
}

From source file:org.voltdb.ClientInterface.java

public ListenableFutureTask<?> processFinishedCompilerWork(final AsyncCompilerResult result) {
    /*//from ww w  .  j  av  a2 s  . co  m
     * 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;
}