Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save ittaiz/8134058 to your computer and use it in GitHub Desktop.

Select an option

Save ittaiz/8134058 to your computer and use it in GitHub Desktop.
cancelling a scheduled future while it is running has no effect
@Test
public void cancellingAScheduledFutureWhileItIsRunningHasNoEffect() {
DeterministicScheduler deterministicScheduler = new DeterministicScheduler();
SchedulerContainer schedulerContainer = new SchedulerContainer(deterministicScheduler);
schedulerContainer.scheduleSelfCancellingTask();
deterministicScheduler.tick(2,TimeUnit.SECONDS);
assertThat(schedulerContainer.runCount(), is(1));
}
public static class SchedulerContainer {
private final ScheduledExecutorService scheduler;
private ScheduledFuture<?> scheduledFuture;
private final AtomicInteger counter = new AtomicInteger();
public SchedulerContainer(ScheduledExecutorService scheduler) {
this.scheduler = scheduler;
}
public void scheduleSelfCancellingTask(){
scheduledFuture = scheduler.scheduleAtFixedRate(
new CancellingRunnable(), 1, 1, TimeUnit.SECONDS);
}
public int runCount(){
return counter.get();
}
private class CancellingRunnable implements Runnable{
@Override
public void run() {
scheduledFuture.cancel(true);
counter.incrementAndGet();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment