Interface TimeService
- All Known Implementing Classes:
TimeService.DisabledTimeService, TimeService.SystemTimeService
Direct calls to System.nanoTime() and Instant.now() scatter through the codebase and make unit tests
dependent on real time. TimeService centralizes all time reads behind a single interface so that:
- Tests can supply a controlled implementation with deterministic timestamps.
- Metrics collection can be disabled at the source
Wall-Clock vs Monotonic Time
The interface provides both kinds of time:
now(): wall-clockInstant, suitable for human-readable timestamps.nanos()andinterval(long): monotonic nanoseconds, suitable for latency measurement or timeouts. Monotonic time is immune to clock adjustments and NTP drift.
Obtaining an Instance
Use the factory method create(boolean). Pass true to get a live time source backed by the
system time source, or false to get a no-op implementation that returns zero/null for all methods.
- Since:
- 2.0
- Author:
- José Bolina
-
Nested Class Summary
Nested ClassesModifier and TypeInterfaceDescriptionstatic final classNo-op implementation that returnsnullfor timestamps and0for nanosecond values.static final classLive implementation backed by the JVM time. -
Method Summary
Modifier and TypeMethodDescriptionstatic TimeServicecreate(boolean enabled) Creates aTimeServiceinstance.longinterval(long start) Computes the elapsed nanoseconds since a previously capturednanos()value.longnanos()Returns a monotonic nanosecond timestamp.now()Returns the current wall-clock time.
-
Method Details
-
now
Instant now()Returns the current wall-clock time.Use this for human-readable timestamps. Do not use for latency measurement, wall-clock time is subject to NTP adjustments.
- Returns:
- the current instant, or
nullwhen the service is disabled
-
nanos
long nanos()Returns a monotonic nanosecond timestamp.Capture a value with
nanos()at the start of an operation, then pass it tointerval(long)to compute the elapsed time. The absolute value has no meaning outside of interval computation.- Returns:
- a monotonic nanosecond value, or
0when disabled
-
interval
long interval(long start) Computes the elapsed nanoseconds since a previously capturednanos()value.Typical usage:
long start = timeService.nanos(); // ... operation ... long elapsedNanos = timeService.interval(start);- Parameters:
start- a value previously returned bynanos()- Returns:
- elapsed nanoseconds, or
0when disabled
-
create
Creates aTimeServiceinstance.- Parameters:
enabled-truefor a live time source,falsefor a no-op implementation- Returns:
- a time service backed by system clocks, or a disabled stub that returns zero/null
-