List of usage examples for java.util.concurrent Future cancel
boolean cancel(boolean mayInterruptIfRunning);
From source file:com.nts.alphamale.handler.ExecutorHandler.java
/** * execute asynchronous commandline// w w w . ja v a 2s .c o m * @param cmdList * @param timeout * @return */ public Map<String, Object> executeAsynchronous(CommandLine cmd, long timeout) { asynchExecutor = Executors.newCachedThreadPool(); Future<Map<String, Object>> future = asynchExecutor .submit(new AsynchronousTask(cmd, ExecuteWatchdog.INFINITE_TIMEOUT)); try { return future.get(); } catch (InterruptedException e) { future.cancel(true); } catch (ExecutionException e) { log.error(e.getMessage()); } return null; }
From source file:com.jbrisbin.vcloud.cache.RabbitMQAsyncCache.java
@Override public void stop(boolean interruptIfRunning) { active.set(false);/*from ww w.ja v a 2s . c o m*/ for (Future<?> f : activeTasks) { f.cancel(interruptIfRunning); } if (interruptIfRunning) { workerPool.shutdownNow(); } else { workerPool.shutdown(); } }
From source file:com.seyren.core.service.schedule.CheckScheduler.java
@Scheduled(fixedRateString = "${GRAPHITE_REFRESH:60000}") public void performChecks() { int checksInScope = 0; int checksWereRun = 0; List<Check> checks = checksStore.getChecks(true, false).getValues(); for (final Check check : checks) { // Skip any not in this instance's workload if (!isMyWork(check)) { continue; }//from w ww. j av a 2 s.com checksInScope++; // See if this check is currently running, if so, return and log the // missed cycle if (!CheckConcurrencyGovernor.instance().isCheckRunning(check)) { checksWereRun++; // Notify the Check Governor that the check is now running CheckConcurrencyGovernor.instance().notifyCheckIsRunning(check); // Submit, so we can get the future, so we can control total time of execution final Future<?> checkExecutionFuture = executor.submit(checkRunnerFactory.create(check)); // Schedule the cancellation (which will be a no-op if it has finished) executor.schedule(new Runnable() { public void run() { checkExecutionFuture.cancel(true); // Log that it was cancelled, if it was terminated if (checkExecutionFuture.isCancelled()) { LOGGER.warn(" *** Check #{} :: Check timed out", check.getId()); // Free this check as a fail-safe to not allow a resource issue to prevent checks from occurring CheckConcurrencyGovernor.instance().notifyCheckIsComplete(check); } } }, this.checkExecutionTimeoutSeconds, TimeUnit.SECONDS); } else { CheckConcurrencyGovernor.instance().logCheckSkipped(check); continue; } } // Log basic information about worker instance and its work LOGGER.info(String.format("Worker %d of %d is responsible for %d of %d checks, of which %d were run.", instanceIndex, totalWorkers, checksInScope, checks.size(), checksWereRun)); }
From source file:org.apache.hadoop.yarn.server.applicationhistoryservice.metrics.timeline.TimelineMetricStoreWatcher.java
/** * Checks TimelineMetricStore functionality by adding and getting * a fake metric to/from HBase/*from w w w. j av a 2 s .co m*/ * @return if check was successful */ private boolean checkMetricStore() { final long startTime = System.currentTimeMillis(); final int delay = configuration.getTimelineMetricsServiceWatcherDelay(); final int timeout = configuration.getTimelineMetricsServiceWatcherTimeout(); TimelineMetric fakeMetric = new TimelineMetric(); fakeMetric.setMetricName(FAKE_METRIC_NAME); fakeMetric.setHostName(FAKE_HOSTNAME); fakeMetric.setAppId(FAKE_APP_ID); fakeMetric.setStartTime(startTime); fakeMetric.setTimestamp(startTime); fakeMetric.getMetricValues().put(startTime, 0.0); final TimelineMetrics metrics = new TimelineMetrics(); metrics.setMetrics(Collections.singletonList(fakeMetric)); Callable<TimelineMetric> task = new Callable<TimelineMetric>() { public TimelineMetric call() throws Exception { timelineMetricStore.putMetrics(metrics); return timelineMetricStore.getTimelineMetric(FAKE_METRIC_NAME, Collections.singletonList(FAKE_HOSTNAME), FAKE_APP_ID, null, startTime - delay * 2 * 1000, startTime + delay * 2 * 1000, Precision.SECONDS, 1); } }; Future<TimelineMetric> future = executor.submit(task); TimelineMetric timelineMetric = null; try { timelineMetric = future.get(timeout, TimeUnit.SECONDS); // Phoenix might throw RuntimeExeption's } catch (Exception e) { return false; } finally { future.cancel(true); } return timelineMetric != null; }
From source file:org.apache.hyracks.api.rewriter.runtime.SuperActivityOperatorNodePushable.java
private void runInParallel(OperatorNodePushableAction opAction) throws HyracksDataException { List<Future<Void>> initializationTasks = new ArrayList<>(); try {//from w w w. j ava2s . c om int index = 0; // Run one action for all OperatorNodePushables in parallel through a thread pool. for (final IOperatorNodePushable op : operatorNodePushablesBFSOrder) { final int opIndex = index++; initializationTasks.add(ctx.getExecutorService().submit(() -> { opAction.runAction(op, opIndex); return null; })); } // Waits until all parallel actions to finish. for (Future<Void> initializationTask : initializationTasks) { initializationTask.get(); } } catch (Throwable th) { for (Future<Void> initializationTask : initializationTasks) { initializationTask.cancel(true); } throw new HyracksDataException(th); } }
From source file:com.anrisoftware.mongoose.environment.EnvironmentImpl.java
private List<Future<?>> cancelTasks(List<Future<?>> tasks) { for (Future<?> future : tasks) { future.cancel(true); }//from ww w . j a va2 s.c o m return tasks; }
From source file:com.verigreen.common.concurrency.timeboundedexecuter.TimeBoundedExecuter.java
private <T> T loopWhileStillNotFinished(final Action<T> actionDelegate, long timeBoundInMillis, Future<T> future, TimeBoundedPolicy policy) { int times = 1; while (true) { try {//from w ww . j a v a2s . c o m return future.get(timeBoundInMillis, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { // was interrupted; should cancel the execution. future.cancel(true); throw new CancellationException(); } catch (ExecutionException e) { // execution ended with an exception. _logger.error("Catastrophic failure when executing a TimeBoundedThread! Exception details: " + e.toString(), e); throw new RuntimeException(e); } catch (TimeoutException e) { // timed out reportAndActAccordingToTimeoutOption(actionDelegate, timeBoundInMillis, future, times, policy); times += 1; } catch (CancellationException e) { // was canceled throw e; } } }
From source file:org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.ContainerLocalizer.java
protected void localizeFiles(LocalizationProtocol nodemanager, CompletionService<Path> cs, UserGroupInformation ugi) throws IOException, YarnException { while (true) { try {/*from w ww . j av a 2s . c om*/ LocalizerStatus status = createStatus(); LocalizerHeartbeatResponse response = nodemanager.heartbeat(status); switch (response.getLocalizerAction()) { case LIVE: List<ResourceLocalizationSpec> newRsrcs = response.getResourceSpecs(); for (ResourceLocalizationSpec newRsrc : newRsrcs) { if (!pendingResources.containsKey(newRsrc.getResource())) { pendingResources.put(newRsrc.getResource(), cs.submit(download(new Path(newRsrc.getDestinationDirectory().getFile()), newRsrc.getResource(), ugi))); } } break; case DIE: // killall running localizations for (Future<Path> pending : pendingResources.values()) { pending.cancel(true); } status = createStatus(); // ignore response while dying. try { nodemanager.heartbeat(status); } catch (YarnException e) { // Cannot do anything about this during death stage, let's just log // it. e.printStackTrace(System.out); LOG.error("Heartbeat failed while dying: ", e); } return; } cs.poll(1000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { return; } catch (YarnException e) { // TODO cleanup throw e; } } }
From source file:org.hupo.psi.mi.psicquic.registry.PsicquicRegistryStatusChecker.java
private void checkAndResumeRegistryTasks() { for (Future f : runningTasks) { try {/*w w w . j ava 2 s. c o m*/ f.get(threadTimeOut, TimeUnit.SECONDS); } catch (InterruptedException e) { log.error("The registry task was interrupted, we cancel the task.", e); if (!f.isCancelled()) { f.cancel(true); } } catch (ExecutionException e) { log.error("The registry task could not be executed, we cancel the task.", e); if (!f.isCancelled()) { f.cancel(true); } } catch (TimeoutException e) { log.error("Service task stopped because of time out " + threadTimeOut + " seconds."); if (!f.isCancelled()) { f.cancel(true); } } catch (Throwable e) { log.error("Service task stopped.", e); if (!f.isCancelled()) { f.cancel(true); } } } runningTasks.clear(); }