Skip to content
Bill La Forge edited this page Nov 18, 2015 · 4 revisions

Transaction ids are handy things. They should be ascending to make it easy to determine the order in which transactions were executed. And they should be unique. And a transaction log really must contain the transaction ids.

For efficiency considerations, we often want to log transactions before they are processed, though this means that the log does not identify which transactions completed successfully. An issue then is how to create unique transaction ids. Tracking transaction ids in a disk file could get complicated, especially if that file is separate from the file(s) of the database itself. OK, it is not that complicated, but gets interesting when you start factoring in various failure scenarios.

But we can make a few assumptions that might simplify things. For example, a restart will never take less than a millisecond. And we will never have more than a thousand transactions in a millisecond. Given these constraints, it is easy enough to create unique timestamps based on the time in milliseconds. We just use

(+ (bit-shift-left (System/currentTimeMillis)) count)

Where count is a counter that is reset every millisecond. Now all we need is an atom to ensure thread safety and perhaps a Thread/yield to guarantee that there can never be more than a thousand timestamps issued in any given millisecond.

Code, Test-code

Clone this wiki locally