Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

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

Select an option

Save ittaiz/8133777 to your computer and use it in GitHub Desktop.
tests which check how jmock and jdk handle canceling a scheduled future while it is running
@Test
public void cancellingAScheduledFutureWhileItIsRunningProhibitsItFromRunningJMock() throws InterruptedException {
final CountDownLatch scheduledHasStarted = new CountDownLatch(1);
final CountDownLatch scheduledHasBeenCancelled = new CountDownLatch(1);
final AtomicInteger counter = new AtomicInteger();
DeterministicScheduler deterministicScheduler = new DeterministicScheduler();
final ScheduledFuture<?> scheduledFuture = deterministicScheduler.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
scheduledHasStarted.countDown();
try {
scheduledHasBeenCancelled.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
counter.incrementAndGet();
}
}, 0, 1, TimeUnit.SECONDS);
Executors.newSingleThreadExecutor().submit(new Runnable() {
@Override
public void run() {
try {
scheduledHasStarted.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
scheduledFuture.cancel(false);
scheduledHasBeenCancelled.countDown();
}
});
deterministicScheduler.tick(5,TimeUnit.SECONDS);
assertThat(counter.get(), is(1));
}
@Test
public void cancellingAScheduledFutureWhileItIsRunningProhibitsItFromRunningJdk() throws InterruptedException {
final CountDownLatch scheduledHasStarted = new CountDownLatch(1);
final CountDownLatch scheduledHasBeenCancelled = new CountDownLatch(1);
final AtomicInteger counter = new AtomicInteger();
final ScheduledFuture<?> scheduledFuture = Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
scheduledHasStarted.countDown();
try {
scheduledHasBeenCancelled.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
counter.incrementAndGet();
}
}, 0, 1, TimeUnit.SECONDS);
Executors.newSingleThreadExecutor().submit(new Runnable() {
@Override
public void run() {
try {
scheduledHasStarted.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
scheduledFuture.cancel(false);
scheduledHasBeenCancelled.countDown();
}
});
Thread.sleep(5000L);
assertThat(counter.get(),is(1));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment