CancellableImpl implements Cancellable, Runnable { @Override public void cancel() { synchronized (monitor) { if (!periodicExecutionCancellation.isPresent()) { throw new IllegalStateException("setPeriodicExecutionCancellationCallback has not been called before cancel"); } cancelled = true; if (running) return; } runlet.close(); periodicExecutionCancellation.get().run(); } CancellableImpl(Runlet runlet); @Override void cancel(); @Override void run();  }
@Test public void testCancelWhileIdle() { cancellable.cancel(); assertFalse(executor.isExecutionRunning()); assertTrue(runlet.isClosed()); executor.runAsync(); executor.runToCompletion(3); assertEquals(2, runlet.getRunsStarted()); }
@Test public void testCancelWhileRunning() { runlet.shouldWaitInRun(true); executor.runAsync(); runlet.waitUntilInRun(); assertEquals(3, runlet.getRunsStarted()); assertEquals(2, runlet.getRunsCompleted()); assertTrue(executor.isExecutionRunning()); assertFalse(runlet.isClosed()); cancellable.cancel(); assertTrue(executor.isExecutionRunning()); assertFalse(runlet.isClosed()); runlet.shouldWaitInRun(false); executor.waitUntilRunCompleted(3); assertFalse(executor.isExecutionRunning()); assertTrue(runlet.isClosed()); executor.runToCompletion(4); assertEquals(3, runlet.getRunsStarted()); }