Dale said:
With only a fixed number of bits your sequence numbers could eventually wrap
around and cause duplicate sequence numbers. It would be rare for this to
occur, but I would rather not bet on probabilities and have a solution that
works.
It's not really a probabilistic situation. Initialize a
`long' to zero, and you can increment it more than 9e18 times
before it turns negative. The probability of failure before
that point is zero, exactly.
Now, it's easy to write "9e18" and this may give the idea
that it's easy to increment a sequence number that many times.
Let's say, for purposes of estimation, that we want to run the
application for ten uninterrupted years, counting all the time.
Ten years comprise roughly 3652 days, or about 316e6 seconds.
The counter can't overflow unless we're incrementing it faster
than 9e18/316e6 ~= 29e9 times per second -- for ten solid years.
Moore's Law suggests we'll see 30GHz machines in about 2010.
Put the first one to work incrementing a counter at full
nominal speed (doing nothing much else, I'd guess), and you'll
need to think about scheduling a restart sometime in 2020.
Or 2030, if you were smart enough to initialize the counter
to Long.MIN_VALUE instead of to zero.
Overflowing a `long' by repeated incrementation is not a
matter of any practical concern whatsoever. But if you're
still worried, use a `BigNumber': not only will it handle any
overflow that might occur, but it will also slow down the
counting rate just a trifle ;-)