Example usage for com.google.common.util.concurrent Futures immediateCancelledFuture

List of usage examples for com.google.common.util.concurrent Futures immediateCancelledFuture

Introduction

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

Prototype

@GwtIncompatible("TODO")
@CheckReturnValue
public static <V> ListenableFuture<V> immediateCancelledFuture() 

Source Link

Document

Creates a ListenableFuture which is cancelled immediately upon construction, so that isCancelled() always returns true .

Usage

From source file:com.addthis.meshy.service.file.FileTarget.java

private void startFindTask() {
    try {/*from  ww w  .  ja  va2 s  . c  o  m*/
        if (!canceled.get()) {
            findTask = finderPool.submit(this);
        } else {
            findTask = Futures.immediateCancelledFuture();
            log.debug("skipping execution of canceled file find");
        }
    } catch (RejectedExecutionException ignored) {
        log.warn("dropping find @ queue={} paths={}", finderQueue.size(), paths);
        cancelFindTask();
    }
}

From source file:org.opendaylight.sxp.controller.core.DatastoreAccess.java

/**
 * @param path                 InstanceIdentifier path specifying data
 * @param data                 Data that will be used in operation
 * @param logicalDatastoreType Type of datastore where operation will be held
 * @param <T>                  Any type extending DataObject
 * @return CheckedFuture callback of operation
 */// ww w  . jav  a2  s .c o m
public synchronized <T extends DataObject> CheckedFuture<Void, TransactionCommitFailedException> put(
        InstanceIdentifier<T> path, T data, LogicalDatastoreType logicalDatastoreType) {
    if (!checkParams(path, logicalDatastoreType)) {
        return Futures.makeChecked(Futures.immediateCancelledFuture(), input -> ACCESS_CLOSED_ON_RW);
    }
    Preconditions.checkNotNull(data);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Put {} {}", logicalDatastoreType, path.getTargetType());
    }
    WriteTransaction transaction = bindingTransactionChain.newWriteOnlyTransaction();
    transaction.put(logicalDatastoreType, path, data);
    return transaction.submit();
}

From source file:com.facebook.buck.util.concurrent.ResourcePool.java

private synchronized ListenableFuture<Void> scheduleNewResourceRequest() {
    if (closing.get()) {
        return Futures.immediateCancelledFuture();
    }/*www . j av a 2s  . c  o m*/
    SettableFuture<Void> resourceFuture = SettableFuture.create();
    resourceRequests.add(resourceFuture);
    return resourceFuture;
}

From source file:org.graylog2.buffers.processors.OutputBufferProcessor.java

private Future<?> processMessage(final Message msg, final MessageOutput output,
        final CountDownLatch doneSignal) {
    if (output == null) {
        LOG.error("Output was null!");
        return Futures.immediateCancelledFuture();
    }/*www  .j  av  a2  s .  com*/
    if (!output.isRunning()) {
        LOG.debug("Skipping stopped output {}", output.getClass().getName());
        return Futures.immediateCancelledFuture();
    }

    Future<?> future = null;
    try {
        LOG.debug("Writing message to [{}].", output.getClass());
        if (LOG.isTraceEnabled()) {
            LOG.trace("Message id for [{}]: <{}>", output.getClass(), msg.getId());
        }
        future = executor.submit(new Runnable() {
            @Override
            public void run() {
                try (Timer.Context ignored = processTime.time()) {
                    output.write(msg);
                } catch (Exception e) {
                    LOG.error("Error in output [" + output.getClass() + "].", e);
                } finally {
                    doneSignal.countDown();
                }
            }
        });
    } catch (Exception e) {
        LOG.error("Could not write message batch to output [" + output.getClass() + "].", e);
        doneSignal.countDown();
    }
    return future;
}

From source file:org.opendaylight.sxp.controller.core.DatastoreAccess.java

/**
 * @param path                 InstanceIdentifier path specifying data
 * @param logicalDatastoreType Type of datastore where operation will be held
 * @param <T>                  Any type extending DataObject
 * @return CheckedFuture callback of operation
 *//*from  ww w.  jav a  2  s .c o  m*/
public synchronized <T extends DataObject> CheckedFuture<Optional<T>, ReadFailedException> read(
        InstanceIdentifier<T> path, LogicalDatastoreType logicalDatastoreType) {
    if (!checkParams(path, logicalDatastoreType)) {
        return Futures.makeChecked(Futures.immediateCancelledFuture(), input -> ACCESS_CLOSED_ON_R);
    }
    try (ReadOnlyTransaction transaction = bindingTransactionChain.newReadOnlyTransaction()) {
        return transaction.read(logicalDatastoreType, path);
    }
}

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  ww .  j  a  va 2 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:com.tinspx.util.net.Requests.java

/**
 * Wraps {@code delegate}, using {@code executor} to rate limit
 * {@code Request} execution. {@code keyFunction} is used to convert
 * each submitted {@code Request} into a {@code key} that is used to
 * {@link LimitedExecutorService#execute(Object, Runnable) execute} the
 * request. Requests with the same {@code key} will be subject to the same
 * rate limiting. Using {@link #toTopPrivateDomain()} will cause all requests
 * to the same top private domain to be rate limited. {@code keyFunction}
 * may return {@code null} to use the {@code LimitedExecutorService} default
 * key.//from   w w w.  j  av  a 2  s  . c  o m
 *
 * @see #toTopPrivateDomain()
 * @see #toFullDomain()
 * @param delegate the {@code RequestContext} to rate limit
 * @param executor the {@code LimitedExecutorService} that is used to rate
 * limit requests
 * @param keyFunction converts each {@code Request} into the key passed to
 * {@code executor} to enforce the rate limiting
 * @return a {@code RequestContext} using {@code executor} to rate limit
 * {@code delegate}
 */
public static RequestContext limit(final @NonFinal AsyncFunction<? super Request, Response> delegate,
        final @NonFinal LimitedExecutorService executor,
        final @NonFinal Function<? super Request, ? extends Object> keyFunction) {
    return new RequestContext() {
        @Override
        public ListenableFuture<Response> apply(Request request) throws Exception {
            request.checkNotStarted();
            if (request.isCancelled()) {
                request.onCancel(this, true);
                return Futures.immediateCancelledFuture();
            }
            request.setSubmissionMillisIfAbsent();
            SettableFuture<Response> future = SettableFuture.create();
            Runnable task = Requests.apply(delegate, request, future);
            Object key = keyFunction.apply(request);
            if (key != null) {
                executor.execute(key, task, future);
            } else {
                executor.execute(task, future);
            }
            return future;
        }
    };
}

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

public Future<?> submitUserDefined(final ColumnFamilyStore cfs, final Collection<Descriptor> dataFiles,
        final int gcBefore) {
    Runnable runnable = new WrappedRunnable() {
        protected void runMayThrow() throws IOException {
            // look up the sstables now that we're on the compaction executor, so we don't try to re-compact
            // something that was already being compacted earlier.
            Collection<SSTableReader> sstables = new ArrayList<>(dataFiles.size());
            for (Descriptor desc : dataFiles) {
                // inefficient but not in a performance sensitive path
                SSTableReader sstable = lookupSSTable(cfs, desc);
                if (sstable == null) {
                    logger.info("Will not compact {}: it is not an active sstable", desc);
                } else {
                    sstables.add(sstable);
                }/*from www .  jav  a  2 s .  c o  m*/
            }

            if (sstables.isEmpty()) {
                logger.info("No files to compact for user defined compaction");
            } else {
                AbstractCompactionTask task = cfs.getCompactionStrategy().getUserDefinedTask(sstables,
                        gcBefore);
                if (task != null)
                    task.execute(metrics);
            }
        }
    };
    if (executor.isShutdown()) {
        logger.info("Compaction executor has shut down, not submitting task");
        return Futures.immediateCancelledFuture();
    }

    return executor.submit(runnable);
}

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

public Future<?> submitCacheWrite(final AutoSavingCache.Writer writer) {
    Runnable runnable = new Runnable() {
        public void run() {
            if (!AutoSavingCache.flushInProgress.add(writer.cacheType())) {
                logger.trace("Cache flushing was already in progress: skipping {}", writer.getCompactionInfo());
                return;
            }/*from   ww  w. jav a2 s.  com*/
            try {
                metrics.beginCompaction(writer);
                try {
                    writer.saveCache();
                } finally {
                    metrics.finishCompaction(writer);
                }
            } finally {
                AutoSavingCache.flushInProgress.remove(writer.cacheType());
            }
        }
    };
    if (executor.isShutdown()) {
        logger.info("Executor has shut down, not submitting background task");
        Futures.immediateCancelledFuture();
    }
    return executor.submit(runnable);
}