Florian Rand
Designer & Software Engineering

Removing a 100ms Thread.sleep

JavaKubernetesTesting

While looking for something to contribute to the Kubernetes Java client, I came across an issue tracking the use of Thread.sleep() in the test suite.

One particular instance caught my attention in EventCorrelatorTest:

Thread.sleep(100);

Unlike other instances where a sleep might be used to wait for an asynchronous operation, this one appeared to be there simply to ensure that two timestamps were different.

It seemed like a good candidate for a small contribution and an opportunity to familiarize myself with the codebase.

It turned out to be a bit more interesting than I anticipated.

A bit of software archaeology

Before removing the sleep, I wanted to understand why it was there in the first place.

Looking through the history of the implementation, I found that the code had previously used Joda-Time’s DateTime before migrating to Java’s OffsetDateTime.

The test itself processes a sequence of Kubernetes events and checks how the event correlator handles duplicates and aggregates similar events. Among other things, it verifies that the timestamp of the last observation differs from that of the first.

The sleep introduces a delay between those observations.

There was no asynchronous operation to wait for. The test simply needed two different timestamps.

My initial approach was to remove the sleep and see what happened.

The tests passed locally, so I opened a pull request.

Windows enters the conversation

The pull request received approval, but the CI pipeline revealed something I hadn’t encountered locally: timestamp assertions were failing on Windows.

Two consecutive calls to OffsetDateTime.now() could return the same value.

Rather than relying on the system clock to advance, I proposed explicitly advancing the timestamp in the test:

OffsetDateTime now = OffsetDateTime.now();

// Process previous events...

now = now.plusNanos(10);

This should give us two distinct timestamps regardless of how quickly the test executes.

After discussing the alternative with the maintainer, I updated the pull request.

The tests passed locally, on Linux and macOS CI, and in some Windows CI runs.

But not consistently.

Reproducing something that doesn’t want to be reproduced

The intermittent nature of the failures made things particularly interesting.

I set up a Windows 10 virtual machine and tried to reproduce the CI environment as closely as possible, using Eclipse Temurin JDK 11, 17 and 21, Bazel 7.4.1 and the same --config ci configuration.

At one point, the tests were passing without any further changes to the code.

Increasing the timestamp increment was an obvious thing to try, but I wasn’t particularly comfortable with changing a number until the tests happened to pass. That wouldn’t be much different from introducing another sleep.

I started instrumenting the test, inspecting the timestamps and experimenting with different increments.

Timestamp incrementObservation
0 nsReproduced duplicate-event assertion failures
10 nsIntermittent CI failures
1,000 nsFive uncached local test runs passed
1 msLocal tests passed across all three JDK versions

Increasing the increment to one millisecond appeared to address the initial failures.

However, subsequent Windows CI runs failed on a different parameterized test case: [6], which tests repeated aggregation of similar events.

Something else was going on.

Following the timestamps

While investigating the failures, I asked about the code on Libera.Chat.

Another developer, julemand101, took a look and left a comment directly on the pull request, pointing out something I had completely overlooked.

Inside EventAggregator.aggregate():

OffsetDateTime now = OffsetDateTime.now();

The aggregator was obtaining its own timestamp.

My changes to the timestamps supplied by the test were potentially irrelevant.

However, after tracing the execution through the correlator, I noticed that this didn’t explain all the failures either.

There were actually two different paths through the implementation:

EventCorrelator
    |
    v
EventAggregator
    |
    +-- Original event
    |
    +-- Newly aggregated event
    |
    v
EventLogger

When dealing with ordinary duplicate events, EventAggregator returns the original event. EventLogger restores the timestamp of the first observation while preserving the incoming lastTimestamp.

In this path, explicitly advancing the timestamp supplied by the test makes sense.

But when the aggregation threshold is reached, EventAggregator creates an entirely new event, assigning both timestamps from its own call to OffsetDateTime.now().

When another aggregated event is processed, EventLogger restores the previous firstTimestamp while retaining the newly generated lastTimestamp.

If those two clock readings happen to return the same value, the assertion fails.

The event has been correctly aggregated and counted. The test fails because of an assumption about time.

This also explained why increasing the input timestamp increment didn’t resolve case [6]. The aggregator was replacing those timestamps.

A detour into OpenJDK

At this point, I was curious about the apparent differences between operating systems and JDK versions.

I started looking through the OpenJDK source code, following how Java obtains time from the underlying operating system.

The Windows implementations I inspected for JDK 11 and 17 used GetSystemTimeAsFileTime().

One interesting detail is that Windows represents these timestamps in units of 100 nanoseconds. However, the representation of a timestamp and the effective resolution of the clock are two different things.

A timestamp can represent a difference of 100 nanoseconds without the clock necessarily being capable of observing that difference.

Similarly, Java’s OffsetDateTime supports nanosecond precision, but that doesn’t guarantee that consecutive calls to now() will produce distinct values.

The behavior observed in CI was consistent with a clock whose value hadn’t advanced between observations.

Unfortunately, I couldn’t directly measure the effective clock resolution of the Windows CI runners.

But did I actually need Windows to reproduce the failure?

Reproducing the mechanism

Instead of continuing to experiment with different Windows environments, I temporarily modified EventAggregator to simulate a clock with a much coarser resolution:

OffsetDateTime now =
    OffsetDateTime.now().truncatedTo(ChronoUnit.SECONDS);

Running the test on Linux produced the same assertion failure in case [6].

Finally, something reproducible.

This didn’t establish the exact clock resolution of the Windows runners, but it demonstrated that the failure could occur independently of Windows or any particular JDK version.

The test was relying on successive system-clock readings returning different values.

The original sleep made that more likely, but it didn’t remove the dependency.

Looking at the Go implementation

Before making further changes to the Java implementation, I decided to look at how the Kubernetes Go client handles event correlation.

The two implementations share similar aggregation logic, but there was an interesting difference: the Go correlator accepts an injectable clock.

Its tests use SimpleIntervalClock, which advances time predictably.

The mechanism I was looking for already existed in another implementation of the same client.

There was no need to reproduce the entire clock abstraction in Java. For this particular change, a standard functional interface was sufficient:

Supplier<OffsetDateTime>

I added a constructor to EventCorrelator that accepts a timestamp supplier, retaining the existing constructor and delegating to it with the default implementation:

public EventCorrelator() {
    this(OffsetDateTime::now);
}

The supplier is passed to EventAggregator, where the direct system-clock call becomes:

OffsetDateTime now = this.now.get();

Production code continues to obtain the current time in exactly the same way.

The test, however, can now supply its own advancing source of timestamps:

AtomicReference<OffsetDateTime> time =
    new AtomicReference<>(OffsetDateTime.now());

EventCorrelator correlator = new EventCorrelator(
    () -> time.getAndUpdate(t -> t.plusSeconds(1))
);

Each invocation returns the current value and advances it by one second, independently of how much actual time has elapsed.

The input timestamps are also advanced explicitly to account for the duplicate-event path.

Both paths are now controlled by the test, and the original assertions remain intact.

Removing the sleep, finally

After reverting the temporary clock-truncation experiment, I ran the full Bazel test suite locally.

All 113 test targets passed.

The change was subsequently approved and merged in PR #4927.

What I initially expected to be a small test cleanup ended up taking me through the history of the implementation, a Windows virtual machine, conversations on IRC, the internals of the event correlator, OpenJDK source code and the equivalent Go implementation.

The final change was relatively small, particularly compared to the amount of code I ended up reading.

That’s probably what I enjoyed most about this contribution.

← Back to notes
2026 · rev 1014abd