|
28 | 28 | import java.util.concurrent.atomic.AtomicReference;
|
29 | 29 |
|
30 | 30 | import static org.hamcrest.Matchers.containsString;
|
31 |
| -import static org.hamcrest.Matchers.equalTo; |
32 | 31 | import static org.hamcrest.Matchers.instanceOf;
|
| 32 | +import static org.hamcrest.Matchers.oneOf; |
33 | 33 | import static org.hamcrest.Matchers.sameInstance;
|
34 | 34 | import static org.mockito.ArgumentMatchers.any;
|
35 | 35 | import static org.mockito.Mockito.mock;
|
@@ -273,25 +273,28 @@ public ScheduledCancellable schedule(Runnable command, TimeValue delay, String e
|
273 | 273 | assertTrue(reschedulingRunnable.isCancelled());
|
274 | 274 | }
|
275 | 275 |
|
276 |
| - public void testRunnableDoesNotRunAfterCancellation() throws Exception { |
277 |
| - final int iterations = scaledRandomIntBetween(2, 12); |
| 276 | + public void testRunnableRunsAtMostOnceAfterCancellation() throws Exception { |
| 277 | + final var intervalMillis = randomLongBetween(1, 50); |
278 | 278 | final AtomicInteger counter = new AtomicInteger();
|
279 |
| - final CountDownLatch doneLatch = new CountDownLatch(iterations); |
| 279 | + final CountDownLatch doneLatch = new CountDownLatch(scaledRandomIntBetween(1, 12)); |
280 | 280 | final Runnable countingRunnable = () -> {
|
281 | 281 | counter.incrementAndGet();
|
282 | 282 | doneLatch.countDown();
|
283 | 283 | };
|
284 | 284 |
|
285 |
| - final TimeValue interval = TimeValue.timeValueMillis(50L); |
286 |
| - final Cancellable cancellable = threadPool.scheduleWithFixedDelay(countingRunnable, interval, Names.GENERIC); |
287 |
| - doneLatch.await(); |
288 |
| - cancellable.cancel(); |
289 |
| - |
290 |
| - final int counterValue = counter.get(); |
291 |
| - assertThat(counterValue, equalTo(iterations)); |
292 |
| - |
| 285 | + final Cancellable cancellable = threadPool.scheduleWithFixedDelay( |
| 286 | + countingRunnable, |
| 287 | + TimeValue.timeValueMillis(intervalMillis), |
| 288 | + Names.GENERIC |
| 289 | + ); |
| 290 | + safeAwait(doneLatch); |
| 291 | + assertTrue(cancellable.cancel()); |
| 292 | + final var iterations = counter.get(); |
293 | 293 | if (rarely()) {
|
294 |
| - assertBusy(() -> assertThat(counter.get(), equalTo(iterations)), 5 * interval.millis(), TimeUnit.MILLISECONDS); |
| 294 | + Thread.sleep(randomLongBetween(0, intervalMillis * 5)); |
| 295 | + } else if (randomBoolean()) { |
| 296 | + Thread.yield(); |
295 | 297 | }
|
| 298 | + assertThat(counter.get(), oneOf(iterations, iterations + 1)); |
296 | 299 | }
|
297 | 300 | }
|
0 commit comments