System time

The system time is provided by the operating system internal clocking algorithm. The programmable interval timer periodically sends an interrupt signal (with a frequency of 1.193182 MHz). The CPU receives the time interruption and increments a tick counter.

Both Unix and Window record time as the number of ticks since a predefined absolute time reference (an epoch). The operating system clock resolution varies from 1ms (Android) to 100ns (Windows) and to 1ns (Unix).

Monotonic time

To order events, the version must advance monotonically. While incrementing a local counter is a monotonic function, system time might not always return monotonic timestamps.

Java has two ways of fetching the current system time. You can either use:

TIMESTAMP(12) may use up to 12 fractional digits (picosecond precision).

When it comes to persisting timestamps, most database servers offer at least 6 fractional digits. MySQL users have long been waiting for a more precise temporal type and the 5.6.4 version had finally added microsecond precision.

On a pre-5.6.4 MySQL database server, updates might be lost during the lifespan of any given second. That’s because all transactions updating the same database row will see the same version timestamp (which points to the beginning of the currently running second).

Argument 2: Pre-5.6.4 MySQL versions only support second precision timestamps.

Handling time is not that easy

Incrementing a local version number is always safer because this operation doesn’t depend on any external factors. If the database row already contains a higher version number your data has become stale. It’s as simple as that.

It took 8 versions for Java to finally come up with a mature Date/Time API. Handling time across application layers (from JavaScript to Java middle-ware to database date/time types) makes matters worse.

While Lamport timestamps was defined for multiple distributed nodes event synchronization, database optimistic locking is much simpler, because there is only one node (the database server) where all transactions are synchronized (coming from concurrent client connections).

Argument 4: Distributed computing favors logical clock over physical ones because we are only interested in event ordering anyway.

If you enjoyed this article, I bet you are going to love my Book and Video Courses as well.

Conclusion

Using physical time might seem convenient at first, but it turns out to be a naive solution. In a distributed environment, perfect system time synchronization is most unlikely. All in all, you should always prefer logical clocks when implementing an optimistic locking mechanism.

Subscribe to our Newsletter

* indicates required

Email Address *

10 000readers have found this blog worth following!

If you subscribeto my newsletter, you'll get:

A free sampleof my Video Course about running Integration tests at warp-speed using Docker and tmpfs