Example usage for java.util.concurrent Future cancel

List of usage examples for java.util.concurrent Future cancel

Introduction

In this page you can find the example usage for java.util.concurrent Future cancel.

Prototype

boolean cancel(boolean mayInterruptIfRunning);

Source Link

Document

Attempts to cancel execution of this task.

Usage

From source file:org.apache.sling.replication.rule.impl.ReplicateOnQueueEventRule.java

public void undo(String ruleString, ReplicationAgent agent) {
    Future<HttpResponse> httpResponseFuture = requests.remove(agent.getName());
    if (httpResponseFuture != null) {
        httpResponseFuture.cancel(true);
    }/*  w  w w  . j av  a2 s.c o  m*/
}

From source file:org.activiti.extension.cache.MemcachedManager.java

/**
 * Set, ??updateTimeout, ?false??./*from  w w  w.  j a va  2  s  . co  m*/
 */
@ManagedOperation(description = "Set, ??updateTimeout, ?false??.")
@ManagedOperationParameters({ @ManagedOperationParameter(name = "key", description = "key"),
        @ManagedOperationParameter(name = "expiration", description = "expiration"),
        @ManagedOperationParameter(name = "value", description = "value") })
public boolean safeSet(String key, int expiration, Object value) {
    Future<Boolean> future = memcachedClient.set(key, expiration, value);
    try {
        return future.get(updateTimeout, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        future.cancel(false);
    }
    return false;
}

From source file:bear.core.AbstractConsole.java

public void stopStreamCopiers() {
    //        logger.debug("OOOOOOOOOOOOPS - stopStreamCopiers", new Exception());

    for (int i = 0; i < copiers.size(); i++) {
        copiers.get(i).stop();//w w w.  ja  va  2  s .  c o m
        final Future future = futures.get(i);

        if (!future.isDone()) {
            future.cancel(true);
        }
    }
}

From source file:org.pssframework.cache.MemcachedImpl.java

public boolean safeAdd(String key, Object value, int expiration) {
    Future<Boolean> future = client.add(key, expiration, value, serializingTranscoder);
    try {//  www .  j  ava 2s  .  com
        return future.get(1, TimeUnit.SECONDS);
    } catch (Exception e) {
        future.cancel(false);
    }
    return false;
}

From source file:org.pssframework.cache.MemcachedImpl.java

public boolean safeSet(String key, Object value, int expiration) {
    Future<Boolean> future = client.set(key, expiration, value, serializingTranscoder);
    try {//from w  ww .jav a 2  s . c om
        return future.get(1, TimeUnit.SECONDS);
    } catch (Exception e) {
        future.cancel(false);
    }
    return false;
}

From source file:org.pssframework.cache.MemcachedImpl.java

public Map<String, Object> get(String[] keys) {
    Future<Map<String, Object>> future = client.asyncGetBulk(serializingTranscoder, keys);
    try {//from w w w.  j  a va2 s . co  m
        return future.get(1, TimeUnit.SECONDS);
    } catch (Exception e) {
        future.cancel(false);
    }
    return new HashMap<String, Object>();
}

From source file:org.pssframework.cache.MemcachedImpl.java

public boolean safeReplace(String key, Object value, int expiration) {
    Future<Boolean> future = client.replace(key, expiration, value, serializingTranscoder);
    try {//from   w ww .ja  v a  2 s  .c  o  m
        return future.get(1, TimeUnit.SECONDS);
    } catch (Exception e) {
        future.cancel(false);
    }
    return false;
}

From source file:org.apache.solr.handler.component.SearchHandler.java

void cancelAll() {
    for (Future<ShardResponse> future : pending) {
        future.cancel(true);
    }
}

From source file:com.ctrip.infosec.rule.executor.PreRulesExecutorService.java

/**
 * // w ww  . j a  v a  2 s. com
 */
void executeParallel(final RiskFact fact, List<PreRule> matchedRules) {

    final StatelessPreRuleEngine statelessPreRuleEngine = SpringContextHolder
            .getBean(StatelessPreRuleEngine.class);
    final String _logPrefix = Contexts.getLogPrefix();
    final String _traceLoggerParentTransId = TraceLogger.getTransId();

    List runs1 = Lists.newArrayList();
    for (final PreRule rule : matchedRules) {

        // ???
        boolean matched = Configs.match(rule.getConditions(), rule.getConditionsLogical(), fact.eventBody);
        if (!matched) {
            continue;
        }

        final String packageName = rule.getRuleNo();
        runs1.add(new Callable<Boolean>() {

            @Override
            public Boolean call() throws Exception {
                RuleMonitorHelper.newTrans(fact, RuleMonitorType.PRE_RULE, packageName);
                TraceLogger.beginTrans(fact.eventId);
                TraceLogger.setParentTransId(_traceLoggerParentTransId);
                TraceLogger.setLogPrefix("[" + packageName + "]");
                Contexts.setPolicyOrRuleNo(packageName);
                long start = System.currentTimeMillis();
                try {
                    // add current execute ruleNo and logPrefix before execution
                    fact.ext.put(Constants.key_ruleNo, rule.getRuleNo());
                    fact.ext.put(Constants.key_isAsync, true);
                    if (rule.getRuleType() == RuleType.Script) {
                        statelessPreRuleEngine.execute(packageName, fact);
                    } else if (rule.getRuleType() == RuleType.Visual) {
                        PreActionEnums preAction = PreActionEnums.parse(rule.getPreAction());
                        if (preAction != null) {
                            Converter converter = converterLocator.getConverter(preAction);
                            converter.convert(preAction, rule.getPreActionFieldMapping(), fact,
                                    rule.getPreActionResultWrapper(), false);
                        }
                    }
                    // remove current execute ruleNo when finished execution.
                    fact.ext.remove(Constants.key_ruleNo);
                    fact.ext.remove(Constants.key_isAsync);
                } catch (Throwable ex) {
                    logger.warn(_logPrefix + "?. preRule: " + packageName
                            + ", exception: " + ex.getMessage());
                    TraceLogger.traceLog("EXCEPTION: " + ex.toString());
                } finally {
                    long handlingTime = System.currentTimeMillis() - start;
                    if (handlingTime > 100) {
                        logger.info(_logPrefix + "preRule: " + packageName + ", usage: " + handlingTime + "ms");
                    }
                    TraceLogger.traceLog("[" + packageName + "] usage: " + handlingTime + "ms");
                    TraceLogger.commitTrans();
                    RuleMonitorHelper.commitTrans2Trunk(fact);
                    Contexts.clearLogPrefix();
                }
                return true;
            }
        });

    }

    // run
    try {
        if (!runs1.isEmpty()) {
            List<Future<Boolean>> results = ParallelExecutorHolder.excutor.invokeAll(runs1, timeout,
                    TimeUnit.MILLISECONDS);
            for (Future f : results) {
                try {
                    if (!f.isDone()) {
                        f.cancel(true);
                    }
                } catch (Exception e) {
                    // ignored
                }
            }
        }
    } catch (Exception ex) {
        // ignored
    }
}

From source file:com.cognifide.aet.job.common.collectors.source.SourceCollector.java

private byte[] getContent() throws ProcessingException {
    byte[] content;
    ExecutorService executor = Executors.newCachedThreadPool();
    Callable<Object> task = new Callable<Object>() {
        @Override/*w  w  w. ja va  2 s. co  m*/
        public Object call() throws IOException {
            return httpRequestBuilder.executeRequest().getContent();
        }
    };
    Future<Object> future = executor.submit(task);
    try {
        content = (byte[]) future.get(timeoutValue, TimeUnit.MILLISECONDS);
    } catch (TimeoutException | InterruptedException | ExecutionException e) {
        throw new ProcessingException(e.getMessage(), e);
    } finally {
        future.cancel(true);
    }
    return content;
}