I'm preparing a Java library that need to assign a unique id to the generated objects for serialization purposes. Once a unique id is generated, I have to ensure that the next time I use the library, there is no possibility to reassign an id to an object that I already saved in the past.
Now, I see that many in Stackoverflow suggest to rely on a couple of options, i.e. UUID
, SecureRandom
, but I'm not sure that this classes suits my needs and I'm not sure about how to use them.
Please, can you address myself to the right utility to use and how to generate the id?
Solutions based on utility from Guava/Apache are welcome.
The probability of generating duplicate UUIDs is pretty low. I'm unaware of the probability that 2 UUID instances across different machines generate the same ID, but then UUIDs should be unique across JVMs. I would not go through the trouble of embedding a database just to generate UUIDs. You can use a java UUID
safely.
Alternate solution
If you need a unique ID across multiple invocations of a program, use a database sequence. You can ask the DB to cache the next N numbers of a sequence to make it reasonable fast and the value will be persisted across invocations. UUIDs are more convenient to use, but both solutions will work. If you use a DB, you will get to know the number of object you've serialized.