Skip to content

Commit 7b29402

Browse files
add method to ensure time passes, replace assertBusy
1 parent f1e9d12 commit 7b29402

File tree

1 file changed

+18
-12
lines changed

1 file changed

+18
-12
lines changed

server/src/test/java/org/elasticsearch/common/util/concurrent/TaskExecutionTimeTrackingEsThreadPoolExecutorTests.java

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -141,20 +141,15 @@ public void testFrontOfQueueLatency() throws Exception {
141141
executor.execute(() -> {});
142142
executor.execute(() -> {});
143143

144+
waitForTimeToElapse();
144145
var frontOfQueueDuration = executor.peekMaxQueueLatencyInQueue();
145-
assertBusy(
146-
// Wrap this call in an assertBusy because it's feasible for the thread pool's clock to see no time pass.
147-
() -> assertThat("Expected a task to be queued", frontOfQueueDuration, greaterThan(0L))
148-
);
149-
safeSleep(10);
146+
assertThat("Expected a task to be queued", frontOfQueueDuration, greaterThan(0L));
147+
waitForTimeToElapse();
150148
var updatedFrontOfQueueDuration = executor.peekMaxQueueLatencyInQueue();
151-
assertBusy(
152-
// Again add an assertBusy to ensure time passes on the thread pool's clock and there are no races.
153-
() -> assertThat(
154-
"Expected a second peek to report a longer duration",
155-
updatedFrontOfQueueDuration,
156-
greaterThan(frontOfQueueDuration)
157-
)
149+
assertThat(
150+
"Expected a second peek to report a longer duration",
151+
updatedFrontOfQueueDuration,
152+
greaterThan(frontOfQueueDuration)
158153
);
159154

160155
// Release the first task that's running, and wait for the second to start -- then it is ensured that the queue will be empty.
@@ -460,4 +455,15 @@ long getQueueTimeNanos() {
460455
return queuedTimeTakenNanos;
461456
}
462457
}
458+
459+
/**
460+
* Ensures that the time reported by {@code System.nanoTime()} has advanced. It is otherwise feasible for the clock to report no time
461+
* passing between operations. Call this method if time passing must be guaranteed.
462+
*/
463+
private static void waitForTimeToElapse() throws InterruptedException {
464+
final var startNanoTime = System.nanoTime();
465+
while (TimeUnit.MILLISECONDS.convert(System.nanoTime() - startNanoTime, TimeUnit.NANOSECONDS) <= 100) {
466+
Thread.sleep(100);
467+
}
468+
}
463469
}

0 commit comments

Comments
 (0)