Created
December 26, 2013 13:49
-
-
Save ittaiz/8134058 to your computer and use it in GitHub Desktop.
cancelling a scheduled future while it is running has no effect
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @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