tags:

views:

2887

answers:

3

If I'm using Long uuid = UUID.randomUUID().getMostSignificantBits() how likely is it to get a collision. It cuts of the least significant bits, so there is a possibility that you run into a collision, right?

+12  A: 

Raymond Chen has a really excellent blog post on this:

GUIDs are globally unique, but substrings of GUIDs aren't

Carl Seleborg
+11  A: 

According to the documentation, randomUUID() generates a type 4 UUID.

This means that the six most significant bits are used for some type information and the remaining 122 bits are assigned randomly.

So the most significant half of your UUID contains 58 bits of randomness, which means you on average need to generate 2^29 UUIDs to get a collision (compared to 2^61 for the full UUID).

So I would say that you are rather safe. Note, however that this is absolutely not true for other types of UUIDs, as Carl Seleborg mentions.

Incidentally, you would be slightly better off by using the least significant half of the UUID (or just generating a random long using SecureRandom).

Rasmus Faber
+2  A: 

You are better off just generating a random long value, then all the bits are random. In Java 6, new Random() uses the System.nanoTime() plus a counter as a seed.

There are different levels of uniqueness.

If you need uniqueness across many machines, you could have a central database table for allocating unique ids, or even batches of unique ids.

If you just need to have uniqueness in one app you can just have a counter (or a counter which starts from the currentTimeMillis()*1000 or nanoTime() depending on your requirements)

Peter Lawrey