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

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

Introduction

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

Prototype

boolean cancel(boolean mayInterruptIfRunning);

Source Link

Document

Attempts to cancel execution of this task.

Usage

From source file:dk.ilios.spanner.internal.ExperimentingSpannerRun.java

@Override
public void run() throws InvalidBenchmarkException {

    ImmutableSet<Experiment> allExperiments = selector.selectExperiments(baselineData);

    // TODO(lukes): move this standard-out handling into the ConsoleOutput class?
    stdout.println("Experiment selection: ");
    stdout.println("  Benchmark Methods:   "
            + FluentIterable.from(allExperiments).transform(new Function<Experiment, String>() {
                @Override/*from ww w  .ja  v a2s .co m*/
                public String apply(Experiment experiment) {
                    return experiment.instrumentation().benchmarkMethod().getName();
                }
            }).toSet());
    stdout.println("  Instruments:   "
            + FluentIterable.from(selector.instruments()).transform(new Function<Instrument, String>() {
                @Override
                public String apply(Instrument instrument) {
                    return instrument.name();
                }
            }));
    stdout.println("  User parameters:   " + selector.userParameters());
    stdout.println("  Selection type:    " + selector.selectionType());
    stdout.println();

    stdout.format("This selection yields %s experiments.%n", allExperiments.size());
    stdout.flush();

    // always dry run first.
    ImmutableSet<Experiment> experimentsToRun = dryRun(allExperiments);
    //        if (experimentsToRun.size() != allExperiments.size()) {
    //            stdout.format("%d experiments were skipped.%n", allExperiments.size() - experimentsToRun.size());
    //        }

    //        if (experimentsToRun.isEmpty()) {
    //            throw new InvalidBenchmarkException("All experiments were skipped.");
    //        }
    //
    //        if (options.dryRun()) {
    //            return;
    //        }

    stdout.flush();

    int totalTrials = experimentsToRun.size() * options.getTrialsPrExperiment();
    Stopwatch stopwatch = Stopwatch.createStarted();
    List<ScheduledTrial> trials = createScheduledTrials(experimentsToRun, totalTrials);

    List<ListenableFuture<Trial.Result>> pendingTrials = scheduleTrials(trials, executorProvider);
    ConsoleOutput output = new ConsoleOutput(stdout, totalTrials, stopwatch);
    try {
        // Process results as they complete.
        for (ListenableFuture<Trial.Result> trialFuture : inCompletionOrder(pendingTrials)) {
            try {
                Trial.Result result = trialFuture.get();
                output.processTrial(result);
                for (ResultProcessor resultProcessor : resultProcessors) {
                    resultProcessor.processTrial(result.getTrial());
                }
            } catch (ExecutionException e) {
                if (e.getCause() instanceof TrialFailureException) {
                    output.processFailedTrial((TrialFailureException) e.getCause());
                } else {
                    for (ListenableFuture<?> toCancel : pendingTrials) {
                        toCancel.cancel(true);
                    }
                    throw Throwables.propagate(e.getCause());
                }
            } catch (InterruptedException e) {
                // be responsive to interruption, cancel outstanding work and exit
                for (ListenableFuture<?> toCancel : pendingTrials) {
                    // N.B. TrialRunLoop is responsive to interruption.
                    toCancel.cancel(true);
                }
                throw new RuntimeException(e);
            }
        }
    } finally {
        executorProvider.shutdown();
        output.close();
    }

    for (ResultProcessor resultProcessor : resultProcessors) {
        try {
            resultProcessor.close();
        } catch (IOException e) {
            logger.log(Level.WARNING, "Could not close a result processor: " + resultProcessor, e);
        }
    }
}

From source file:io.soliton.protobuf.EnvelopeServerHandler.java

/**
 * {@inheritDoc}/*from  ww w. ja v a 2 s.c  o  m*/
 */
@Override
public void channelRead0(ChannelHandlerContext context, I request) throws Exception {
    if (!accept(request)) {
        context.fireChannelRead(request);
        return;
    }

    Envelope envelope = null;
    try {
        envelope = convertRequest(request);
    } catch (RequestConversionException rce) {
        serverLogger.logClientError(rce);
        throw rce;
    }

    if (envelope.hasControl() && envelope.getControl().getCancel()) {
        ListenableFuture<?> pending = pendingRequests.remove(envelope.getRequestId());
        if (pending != null) {
            boolean cancelled = pending.cancel(true);
            context.channel().writeAndFlush(Envelope.newBuilder().setRequestId(envelope.getRequestId())
                    .setControl(Control.newBuilder().setCancel(cancelled)).build());
        }
        return;
    }

    Service service = services.lookupByName(envelope.getService());
    if (service == null) {
        serverLogger.logUnknownService(service);
        logger.warning(String.format("Received request for unknown service %s", envelope.getService()));
        context.channel()
                .writeAndFlush(
                        Envelope.newBuilder().setRequestId(envelope.getRequestId())
                                .setControl(Control.newBuilder()
                                        .setError(String.format("Unknown service %s", envelope.getService())))
                                .build());
        return;
    }

    ServerMethod<? extends Message, ? extends Message> method = service.lookup(envelope.getMethod());
    if (method == null) {
        serverLogger.logUnknownMethod(service, envelope.getMethod());
        logger.warning(String.format("Received request for unknown method %s/%s", envelope.getService(),
                envelope.getMethod()));
        context.channel().writeAndFlush(Envelope.newBuilder().setRequestId(envelope.getRequestId())
                .setControl(Control.newBuilder().setError(
                        String.format("Unknown method %s/%s", envelope.getService(), envelope.getMethod())))
                .build());
        return;
    }
    serverLogger.logMethodCall(service, method);
    invoke(method, envelope.getPayload(), envelope.getRequestId(), context.channel());
}

From source file:com.twitter.heron.spi.statemgr.SchedulerStateManagerAdaptor.java

/**
 * Waits for ListenableFuture to terminate. Cancels on timeout
 *//*from  ww w  .j ava 2s  .  c om*/
protected <V> V awaitResult(ListenableFuture<V> future, int time, TimeUnit unit) {
    try {
        return future.get(time, unit);
    } catch (InterruptedException | TimeoutException | ExecutionException e) {
        LOG.log(Level.SEVERE, "Exception processing future ", e);
        future.cancel(true);
        return null;
    }
}

From source file:com.dogecoin.dogecoinj.net.discovery.TorDiscovery.java

private Collection<InetSocketAddress> lookupAddresses(long timeoutValue, TimeUnit timeoutUnit,
        List<Circuit> circuits) throws InterruptedException {
    createThreadPool(circuits.size() * hostNames.length);

    try {/*  ww  w .ja  va 2s  .  c  o m*/
        List<ListenableFuture<Lookup>> lookupFutures = Lists.newArrayList();
        for (final Circuit circuit : circuits) {
            for (final String seed : hostNames) {
                lookupFutures.add(threadPool.submit(new Callable<Lookup>() {
                    @Override
                    public Lookup call() throws Exception {
                        return new Lookup(circuit.getFinalCircuitNode().getRouter(), lookup(circuit, seed));
                    }
                }));
            }
        }

        threadPool.awaitTermination(timeoutValue, timeoutUnit);
        int timeouts = 0;
        for (ListenableFuture<Lookup> future : lookupFutures) {
            if (!future.isDone()) {
                timeouts++;
                future.cancel(true);
            }
        }
        if (timeouts > 0)
            log.warn("{} DNS lookups timed out", timeouts);

        try {
            List<Lookup> lookups = new ArrayList<Lookup>(Futures.successfulAsList(lookupFutures).get());
            // Any failures will result in null entries.  Remove them.
            lookups.removeAll(singleton(null));

            // Use a map to enforce one result per exit node
            // TODO: randomize result selection better
            Map<HexDigest, InetSocketAddress> lookupMap = Maps.newHashMap();

            for (Lookup lookup : lookups) {
                InetSocketAddress address = new InetSocketAddress(lookup.address, netParams.getPort());
                lookupMap.put(lookup.router.getIdentityHash(), address);
            }

            return lookupMap.values();
        } catch (ExecutionException e) {
            // Cannot happen, successfulAsList accepts failures
            throw new RuntimeException(e);
        }
    } finally {
        shutdownThreadPool();
    }
}

From source file:org.apache.druid.query.lookup.KafkaLookupExtractorFactory.java

@Override
public boolean close() {
    synchronized (started) {
        if (!started.get() || executorService.isShutdown()) {
            LOG.info("Already shutdown, ignoring");
            return !started.get();
        }//from w  w w. ja  v  a 2 s  . c  o m
        started.set(false);
        executorService.shutdown();

        if (consumerConnector != null) {
            consumerConnector.shutdown();
        }

        final ListenableFuture<?> future = this.future;
        if (future != null) {
            if (!future.isDone() && !future.cancel(false)) {
                LOG.error("Error cancelling future for topic [%s]", getKafkaTopic());
                return false;
            }
        }
        cacheHandler.close();
        return true;
    }
}

From source file:io.druid.query.lookup.KafkaLookupExtractorFactory.java

@Override
public boolean close() {
    synchronized (started) {
        if (!started.get() || executorService.isShutdown()) {
            LOG.info("Already shutdown, ignoring");
            return !started.get();
        }/* w  w w. j a  v a 2  s . com*/
        started.set(false);
        executorService.shutdown();

        if (consumerConnector != null) {
            consumerConnector.shutdown();
        }

        final ListenableFuture<?> future = this.future;
        if (future != null) {
            if (!future.isDone() && !future.cancel(false)) {
                LOG.error("Error cancelling future for topic [%s]", getKafkaTopic());
                return false;
            }
        }
        if (!cacheManager.delete(factoryId)) {
            LOG.error("Error removing [%s] for topic [%s] from cache", factoryId, getKafkaTopic());
            return false;
        }
        return true;
    }
}

From source file:com.google.caliper.runner.ExperimentingCaliperRun.java

@Override
public void run() throws InvalidBenchmarkException {
    ImmutableSet<Experiment> allExperiments = selector.selectExperiments();
    // TODO(lukes): move this standard-out handling into the ConsoleOutput class?
    stdout.println("Experiment selection: ");
    stdout.println("  Benchmark Methods:   "
            + FluentIterable.from(allExperiments).transform(new Function<Experiment, String>() {
                @Override//from   w  w w  . j a va2  s .  c  om
                public String apply(Experiment experiment) {
                    return experiment.instrumentation().benchmarkMethod().getName();
                }
            }).toSet());
    stdout.println("  Instruments:   "
            + FluentIterable.from(selector.instruments()).transform(new Function<Instrument, String>() {
                @Override
                public String apply(Instrument instrument) {
                    return instrument.name();
                }
            }));
    stdout.println("  User parameters:   " + selector.userParameters());
    stdout.println("  Virtual machines:  "
            + FluentIterable.from(selector.vms()).transform(new Function<VirtualMachine, String>() {
                @Override
                public String apply(VirtualMachine vm) {
                    return vm.name;
                }
            }));
    stdout.println("  Selection type:    " + selector.selectionType());
    stdout.println();

    if (allExperiments.isEmpty()) {
        throw new InvalidBenchmarkException(
                "There were no experiments to be performed for the class %s using the instruments %s",
                benchmarkClass.benchmarkClass().getSimpleName(), instruments);
    }

    stdout.format("This selection yields %s experiments.%n", allExperiments.size());
    stdout.flush();

    // always dry run first.
    ImmutableSet<Experiment> experimentsToRun = dryRun(allExperiments);
    if (experimentsToRun.size() != allExperiments.size()) {
        stdout.format("%d experiments were skipped.%n", allExperiments.size() - experimentsToRun.size());
    }

    if (experimentsToRun.isEmpty()) {
        throw new InvalidBenchmarkException("All experiments were skipped.");
    }

    if (options.dryRun()) {
        return;
    }

    stdout.flush();

    int totalTrials = experimentsToRun.size() * options.trialsPerScenario();
    Stopwatch stopwatch = Stopwatch.createStarted();
    List<ScheduledTrial> trials = createScheduledTrials(experimentsToRun, totalTrials);

    final ListeningExecutorService executor = executorProvider.get();
    List<ListenableFuture<TrialResult>> pendingTrials = scheduleTrials(trials, executor);
    ConsoleOutput output = new ConsoleOutput(stdout, totalTrials, stopwatch);
    try {
        // Process results as they complete.
        for (ListenableFuture<TrialResult> trialFuture : inCompletionOrder(pendingTrials)) {
            try {
                TrialResult result = trialFuture.get();
                output.processTrial(result);
                for (ResultProcessor resultProcessor : resultProcessors) {
                    resultProcessor.processTrial(result.getTrial());
                }
            } catch (ExecutionException e) {
                if (e.getCause() instanceof TrialFailureException) {
                    output.processFailedTrial((TrialFailureException) e.getCause());
                } else {
                    for (ListenableFuture<?> toCancel : pendingTrials) {
                        toCancel.cancel(true);
                    }
                    throw Throwables.propagate(e.getCause());
                }
            } catch (InterruptedException e) {
                // be responsive to interruption, cancel outstanding work and exit
                for (ListenableFuture<?> toCancel : pendingTrials) {
                    // N.B. TrialRunLoop is responsive to interruption.
                    toCancel.cancel(true);
                }
                throw new RuntimeException(e);
            }
        }
    } finally {
        executor.shutdown();
        output.close();
    }

    for (ResultProcessor resultProcessor : resultProcessors) {
        try {
            resultProcessor.close();
        } catch (IOException e) {
            logger.log(WARNING, "Could not close a result processor: " + resultProcessor, e);
        }
    }
}

From source file:org.anhonesteffort.p25.resource.TrafficChannelCaptureResource.java

@POST
@Timed//w  w w . j av  a2  s  .co m
@Path("/group")
public void capture(@NotNull @Valid GroupCaptureRequest request, @Suspended AsyncResponse response) {
    synchronized (txnLock) {
        if (pendingRequests.contains(request.getChannelId())
                || channelMonitor.contains(request.getChannelId())) {
            response.resume(Response.status(409).build());
            return;
        } else {
            pendingRequests.add(request.getChannelId());
            P25DcodrMetrics.getInstance().groupCaptureRequest();
            log.info(request.getChannelId() + " requesting channel");
        }
    }

    ChannelRequest.Reader channelRequest = transform(request);
    ListenableFuture<SamplesSourceHandler> sourceFuture = chnlzr.createSourceFor(channelRequest);

    Futures.addCallback(sourceFuture, new SamplesSourceCallback(request, response));

    response.setTimeout(config.getChannelRequestTimeoutMs(), TimeUnit.MILLISECONDS);
    response.setTimeoutHandler(asyncResponse -> sourceFuture.cancel(true));
}

From source file:org.anhonesteffort.p25.resource.ControlChannelQualifyingResource.java

@POST
@Timed//from   www  . j  a v a 2 s  .  c  o m
@ManagedAsync
public void qualify(@NotNull @Valid QualifyRequest request, @Suspended AsyncResponse response) {
    ChannelRequest.Reader channelRequest = transform(request);
    ListenableFuture<SamplesSourceHandler> sourceFuture = chnlzr.createSourceFor(channelRequest);

    Futures.addCallback(sourceFuture, new SamplesSourceCallback(channelRequest, response));

    response.setTimeout(config.getChannelRequestTimeoutMs(), TimeUnit.MILLISECONDS);
    response.setTimeoutHandler(asyncResponse -> sourceFuture.cancel(true));
}

From source file:org.anhonesteffort.p25.resource.ControlChannelFollowingResource.java

@POST
@Timed/*w  w  w  . ja v a  2s  . c om*/
@ManagedAsync
public void follow(@NotNull @Valid FollowRequest request, @Suspended AsyncResponse response) {
    synchronized (txnLock) {
        if (pendingRequests.contains(request.getChannelId())
                || channelMonitor.contains(request.getChannelId())) {
            response.resume(Response.status(409).build());
            return;
        } else {
            pendingRequests.add(request.getChannelId());
            log.info(request.getChannelId() + " requesting channel");
        }
    }

    ChannelRequest.Reader channelRequest = transform(request);
    ListenableFuture<SamplesSourceHandler> sourceFuture = chnlzr.createSourceFor(channelRequest);

    Futures.addCallback(sourceFuture, new SamplesSourceCallback(request, response));

    response.setTimeout(config.getChannelRequestTimeoutMs(), TimeUnit.MILLISECONDS);
    response.setTimeoutHandler(asyncResponse -> sourceFuture.cancel(true));
}