I’m excited to share an open-source project I’ve been working on called Timestone, a small but handy Java library for abstracting time sources and writing deterministic, testable time-based logic.
Why I Built This
If you’ve written code that deals with:
- session expiration
- retries with timeouts
- scheduled jobs or caches with TTLs
then you know how painful it can be to test anything involving the passage of time.
For instance,
Thread.sleep(1000);
assertTrue(Duration.between(start, Instant.now()).toMillis() > 1000);
This is flaky, slow, and impossible to speed up in unit tests.
While building time-based systems, I noticed that many open-source projects, Apache Kafka and Apache Flink for example, rolled their own fake clocks and manual timers to simulate time. I kept seeing duplicated patterns across internal and public codebases.
In Kafka
It introduces org.apache.kafka.common.utils.Time for abstracting system clocks and simulating time progression in a clean, pluggable way.
In Flink
Flink has org.apache.flink.util.clock.Clock abstract class for retrieving either absolute or relative time.
What is Timestone?
Timestone is a minimal, dependency-free library for abstracting system clocks and simulating time progression in a clean, pluggable way.
Key Components
-
Time: an interface that abstractsInstant.now(),System.currentTimeMillis(), andThread.sleep(). -
MutableTime: lets you manually advance time in unit tests
How It Works
Here is a table of examples on how to use Timestone in your Java projects.
| Production Code | Test Code | Description |
|---|---|---|
| StopWatch.java | StopWatchTest.java | Example of using Time.getInstant() for temporal operations |
| ExponentialBackoff.java | ExponentialBackoffTest.java | Example of using Time.sleep() for thread suspension |
When You Should Use It
- Your code checks timestamps, durations, or elapsed time
- You’re implementing TTLs, retries, backoffs, delays
- You want fast and reliable unit tests
- You want to clean up test setups that rely on threads, timers, or sleeping
I’d Love Feedback
This is the first public release, and I’d love to hear:
- How do you test time-based logic?
- Are there features you’d want added (e.g., auto-advancing clocks, clock hooks)?
Here’s the repo: predatorray/timestone
Feel free to leave feedback, file issues, or just star it if you think it might help others.
Top comments (0)