@Override public final synchronized boolean cancel(boolean mayInterruptIfRunning) { // semantics changed in 2016-01, previously "true" was INTERRUPT_TASK_BUT_NOT_SUBMITTED_TASKS return cancel(mayInterruptIfRunning ? TaskCancellationMode.INTERRUPT_TASK_AND_DEPENDENT_SUBMITTED_TASKS : TaskCancellationMode.DO_NOT_INTERRUPT); }
@Override public final synchronized boolean cancel() { return cancel(true); }
protected boolean cancel(TaskCancellationMode mode, Boolean interruptPrimaryThreadOverride) { if (isDone()) return false; if (log.isTraceEnabled()) log.trace("cancelling DST {}", this); // first do the super's cancel, setting cancelled, and calling doCancel to cancel children boolean result = super.cancel(mode); // then come back and ensure our primary thread is cancelled if needed if (interruptPrimaryThreadOverride==null) interruptPrimaryThreadOverride = mode.isAllowedToInterruptTask(); if (log.isTraceEnabled()) { log.trace("DST cancelling "+this+" mode "+mode+", interruptPrimary "+interruptPrimaryThreadOverride); } synchronized (jobTransitionLock) { if (primaryThread!=null) { if (interruptPrimaryThreadOverride) { if (log.isTraceEnabled()) log.trace("cancelling {} - interrupting", this); primaryThread.interrupt(); } result = true; } } return result; }
fakeTaskForContext.cancel(); try { BasicExecutionManager.getPerThreadCurrentTask().set(fakeTaskForContext);
@Test public void cancelAfterRun() throws Exception { BasicTask<Integer> t = new BasicTask<Integer>(Callables.returning(42)); em.submit(MutableMap.of("tag", "A"), t); assertEquals(t.get(), (Integer)42); t.cancel(true); assertFalse(t.isCancelled()); assertFalse(t.isError()); assertTrue(t.isDone()); }
@Test public void cancelBeforeRun() throws Exception { final CountDownLatch blockForever = new CountDownLatch(1); BasicTask<Integer> t = new BasicTask<Integer>(new Callable<Integer>() { @Override public Integer call() throws Exception { blockForever.await(); return 42; }}); t.cancel(true); assertTrue(t.isCancelled()); assertTrue(t.isDone()); assertTrue(t.isError()); em.submit(MutableMap.of("tag", "A"), t); try { t.get(); fail("get should have failed due to cancel"); } catch (CancellationException e) { // expected } assertTrue(t.isCancelled()); assertTrue(t.isDone()); assertTrue(t.isError()); log.debug("cancelBeforeRun status: {}", t.getStatusDetail(false)); assertTrue(t.getStatusDetail(false).toLowerCase().contains("cancel")); }