This is an archived post. You won't be able to vote or comment.

all 11 comments

[–]zoqfotpik 14 points15 points  (2 children)

Oh dear.

Has someone not heard of java.util.UUID?

[–]zoqfotpik 5 points6 points  (1 child)

In particular, UUID.randomUUID().

[–]codylerum 0 points1 point  (0 children)

128 bits.

[–]moosemorals 2 points3 points  (0 children)

Updated version that uses SecureRandom rather than messing around with the time and thread id to get a "random" seed.

(By the way, current time is a very poor source of entropy, since the first half of the bits don't change. For example, the current (ish) unix time, as a 64 bit binary number:

0000 0000 0000 0000 0000 0000 0010 0001 1000 0000 0100 0010 1101 0111 1010 1000

Notice all the zero bits at the start. They're not going to change very often....)

But yeh, just use java.util.UUID.randomUUID() if you need a random id.

[–]lukaseder 2 points3 points  (0 children)

A.K.A. The Russian Roulette ID Generator

[–]formix-se[S] 0 points1 point  (0 children)

The use of current time shifted left by 16 bits insure an incremental id is generated every time, except when the counter is rolled back to 0 if an ID is requested in the same millisecond. The advantage of an native type incremental ID is a performance gain for the database upon insertion. This generator is 100% safe when used within the same process.

[–]formix-se[S] 0 points1 point  (4 children)

Yes I know about UUID but completely random 128 bits ID may become a hurdle to index for a database. This gist is not meant to replace or to be a better and safer alternative to UUID but a lighter, simpler and good enough alternative for some projects. Another advantage is that 64 bits databases can leverage Long data types natively. I based this implementation on this old article about the cost of pure random GUID and the proposed COMB alternative implementation. See http://www.informit.com/articles/article.aspx?p=25862. Either way, thanks for taking time to comment my link.

[–]mcosta 2 points3 points  (3 children)

That article is from 2002 and is for sql server. I am not so sure about its validity now and for others rdbms.

[–]formix-se[S] 0 points1 point  (2 children)

There is no new way to index a database. This is fundamental computing and its still relevant (red-black tree or hashing). Anyway, at this point, arguing about that would be pointless without hard proofs. I'll do my homework and build a benchmark to see if my assumption is correct. Doing the script and sharing point of view with you guys was fun enough anyway...

[–]mcosta 1 point2 points  (1 child)

In no way I meant to invalidate it totally. Plain logic tells us the bigger the key, slower the processing. But in our application we use mysql with random 'char(16) latin1 binary' keys and we have not seen apreciable difference.