List of usage examples for java.util.concurrent Future cancel
boolean cancel(boolean mayInterruptIfRunning);
From source file:org.apache.syncope.core.provisioning.java.propagation.PriorityPropagationTaskExecutor.java
@Override protected void doExecute(final Collection<PropagationTask> tasks, final PropagationReporter reporter, final boolean nullPriorityAsync) { List<PropagationTask> prioritizedTasks = CollectionUtils.select(tasks, new Predicate<PropagationTask>() { @Override//from w w w .ja v a2 s .c o m public boolean evaluate(final PropagationTask task) { return task.getResource().getPropagationPriority() != null; } }, new ArrayList<PropagationTask>()); Collections.sort(prioritizedTasks, new PriorityComparator()); LOG.debug("Propagation tasks sorted by priority, for serial execution: {}", prioritizedTasks); Collection<PropagationTask> concurrentTasks = CollectionUtils.subtract(tasks, prioritizedTasks); LOG.debug("Propagation tasks for concurrent execution: {}", concurrentTasks); // first process priority resources sequentially and fail as soon as any propagation failure is reported for (PropagationTask task : prioritizedTasks) { TaskExec execution = null; PropagationTaskExecStatus execStatus; try { execution = newPropagationTaskCallable(task, reporter).call(); execStatus = PropagationTaskExecStatus.valueOf(execution.getStatus()); } catch (Exception e) { LOG.error("Unexpected exception", e); execStatus = PropagationTaskExecStatus.FAILURE; } if (execStatus != PropagationTaskExecStatus.SUCCESS) { throw new PropagationException(task.getResource().getKey(), execution == null ? null : execution.getMessage()); } } // then process non-priority resources concurrently... final CompletionService<TaskExec> completionService = new ExecutorCompletionService<>(executor); Map<PropagationTask, Future<TaskExec>> nullPriority = new HashMap<>(concurrentTasks.size()); for (PropagationTask task : concurrentTasks) { try { nullPriority.put(task, completionService.submit(newPropagationTaskCallable(task, reporter))); } catch (Exception e) { LOG.error("Unexpected exception", e); } } // ...waiting for all callables to complete, if async processing was not required if (!nullPriority.isEmpty()) { if (nullPriorityAsync) { for (Map.Entry<PropagationTask, Future<TaskExec>> entry : nullPriority.entrySet()) { reporter.onSuccessOrNonPriorityResourceFailures(entry.getKey(), PropagationTaskExecStatus.CREATED, null, null, null); } } else { final Set<Future<TaskExec>> nullPriorityFutures = new HashSet<>(nullPriority.values()); try { executor.submit(new Runnable() { @Override public void run() { while (!nullPriorityFutures.isEmpty()) { try { nullPriorityFutures.remove(completionService.take()); } catch (Exception e) { LOG.error("Unexpected exception", e); } } } }).get(60, TimeUnit.SECONDS); } catch (Exception e) { LOG.error("Unexpected exception", e); } finally { for (Future<TaskExec> future : nullPriorityFutures) { future.cancel(true); } nullPriorityFutures.clear(); nullPriority.clear(); } } } }
From source file:com.netflix.genie.core.services.impl.JobStateServiceImpl.java
/** * {@inheritDoc}/*from w w w. j a v a 2 s . c o m*/ */ @Override public void done(final String jobId) throws GenieException { this.handle(jobId, () -> { final JobInfo jobInfo = jobs.get(jobId); final Future<?> task = jobInfo.getRunningTask(); if (task != null && !task.isDone()) { if (task.cancel(true)) { log.debug("Successfully cancelled job task for job {}", jobId); } else { log.error("Unable to cancel job task for job {}", jobId); this.unableToCancel.increment(); } } jobs.remove(jobId); return null; }); }
From source file:com.creactiviti.piper.core.Worker.java
/** * Handle control tasks. Control tasks are used by the Coordinator * to control Worker instances. For example to stop an ongoing task * or to adjust something on a worker outside the context of a job. *///from www. j av a2s .c o m public void handle(ControlTask aControlTask) { Assert.notNull(aControlTask, "task must not be null"); if (ControlTask.TYPE_CANCEL.equals(aControlTask.getType())) { String taskId = aControlTask.getRequiredString("taskId"); Future<?> future = taskExecutions.get(taskId); if (future != null) { logger.info("Cancelling task {}", taskId); future.cancel(true); } } }
From source file:eu.europa.ec.fisheries.uvms.plugins.ais.service.AisService.java
@PreDestroy public void destroy() { if (connection != null) { connection.close();//from w w w . j a va2 s.c o m } Iterator<Future<Long>> processIterator = processes.iterator(); while (processIterator.hasNext()) { Future<Long> process = processIterator.next(); if (process.isDone() || process.isCancelled()) { processIterator.remove(); } else { process.cancel(true); } } }
From source file:io.seldon.memcache.ExceptionSwallowingMemcachedClient.java
@Override public Object get(String key) { Object myObj = null;/*w ww .j av a 2 s . c om*/ Future<Object> f = super.asyncGet(hashKey(key)); try { myObj = f.get(500, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { logger.warn("Timeout exception in get ", e); f.cancel(false); } catch (InterruptedException e) { logger.error("Interrupted in get ", e); f.cancel(false); } catch (ExecutionException e) { logger.error("Execution exception in get ", e); f.cancel(false); } return myObj; }
From source file:com.amazonaws.services.s3.UploadObjectObserver.java
/** * Notified from//w ww. ja v a2s . c o m * {@link AmazonS3EncryptionClient#uploadObject(UploadObjectRequest)} when * failed to upload any part. This method is responsible for cancelling * ongoing uploads and aborting the multi-part upload request. */ public void onAbort() { for (Future<?> future : getFutures()) { future.cancel(true); } if (uploadId != null) { try { s3.abortMultipartUpload( new AbortMultipartUploadRequest(req.getBucketName(), req.getKey(), uploadId)); } catch (Exception e) { LogFactory.getLog(getClass()).debug("Failed to abort multi-part upload: " + uploadId, e); } } }
From source file:com.agileEAP.module.cache.memcached.SpyMemcachedClient.java
/** * Delete, ??updateTimeout, ?false??.// w w w . j a v a 2 s . c om */ public boolean safeDelete(String key) { Future<Boolean> future = memcachedClient.delete(key); try { return future.get(updateTimeout, TimeUnit.MILLISECONDS); } catch (Exception e) { future.cancel(false); } return false; }
From source file:com.njmd.framework.utils.memcached.SpyMemcachedClient.java
/** * Set,1, ?false??.//from w ww .j a v a 2 s .co m */ public boolean safeDelete(String key) { Future<Boolean> future = memcachedClient.delete(key); try { return future.get(1, TimeUnit.SECONDS); } catch (Exception e) { future.cancel(false); } return false; }
From source file:iddb.runtime.cache.impl.CacheImpl.java
@Override public Object get(String key) { synchronized (key) { Object obj = null;/*from ww w . j av a 2 s .c o m*/ Future<Object> asGet = client.asyncGet(getNamespace() + "-" + key); try { obj = asGet.get(10, TimeUnit.SECONDS); } catch (TimeoutException e) { asGet.cancel(false); log.error(e.getMessage()); } catch (InterruptedException e) { log.error(e.getMessage()); } catch (ExecutionException e) { log.error(e.getMessage()); } return obj; } }
From source file:com.amazonaws.mobileconnectors.s3.transfermanager.internal.UploadMonitor.java
/** * Cancels the inflight transfers if they are not completed. *//* ww w. j av a 2s .c o m*/ private void cancelFutures() { nextFuture.cancel(true); for (Future<PartETag> f : futures) { f.cancel(true); } multipartUploadCallable.getFutures().clear(); futures.clear(); }