Hybrid Clock
A hybrid logical clock (HLC) that combines a physical clock with a logical component.
It is much like a Lamport clock in that can be used to provide a causal ordering of events. Its advantage over a Lamport clock is that it can additionally order concurrent events using physical time. Note that this advantage is however lost in cases where a participant's physical clock is faulty, especially if it returns times significantly into the future.
Note that the physical component of a timestamp generated by this clock does not necessarily correspond to the actual physical time when the timestamp was generated.
This implementation is thread-safe.
Example instantiation where physical time is expressed as an Instant and logical time as a Long:
import kotlinx.datetime.Clock
import kotlinx.datetime.Instant
fun instantLongHybridClock(
initialTime: HybridTimestamp<Instant, Long>,
onNewTime: suspend (HybridTimestamp<Instant, Long>) -> Unit = {},
physicalClock: Clock = Clock.System
): HybridClock<Instant, Long> = HybridClock(
initialTime,
0,
{ physicalClock.now() },
Long::inc,
onNewTime
)Usage:
// Obtain a new timestamp for an event that occurred locally:
val timestamp = clock.tick()
// Make the clock aware of an event that occurred externally, so it can adjust its external state:
clock.tock(externalTimestamp)Functions
Returns a logical timestamp that is greater than the current logical timestamp of this clock and updates the clock's internal state accordingly.
Updates the internal state of the clock to reflect the occurrence of an external event with the given logical timestamp.