Global unique identifiers in Java, the easy way
A recent attempt at creating a unique identifier at work was shot down in flames by Findbugs. My naïve attempt wasn’t very thoughtful but seemed to work.
Integer.toString(Math.abs(random.nextInt()))
Findbugs indicated there was a possibility that I might end up with a negative value even though I “cleverly” used Math.abs().
RV: Bad attempt to compute absolute value of signed random integer (RV_ABSOLUTE_VALUE_OF_RANDOM_INT)
If the number returned by the random number generator is Integer.MIN_VALUE, then the result will be negative as well
Even though I didn’t need this random id to be perfect — the unintended side-effect wasn’t a technical problem since I used it as a String — I still wanted to fix it. Stackoverflow to the rescue.
A question-and-answer from Stackoverflow pointed the way to the solution: java.util.UUID. Somehow, I missed that Sun had added Java’s own universally unique identifier (UUID) generator in Java 1.5.
In the end, I happily replaced my homemade id generator with Java’s.
UUID.randomUUID().toString()
The output of which is something like 1c312843-8903-411f-88b2-ff1b92ca80ba.
From http://codeaweso.me/2011/11/global-unique-identifiers-in-java-the-easy-way/
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)






Comments
Leen Toelen replied on Thu, 2011/11/10 - 3:26am
Fabrizio Giudici replied on Thu, 2011/11/10 - 3:42am
Given the cited limitation of Java UUID, I use this tiny and very fast library:
http://johannburkard.de/software/uuid/
Aries McRae replied on Thu, 2011/11/10 - 4:15pm
Before Java 5, I used
to generate a unique sequential number.Cloves Almeida replied on Fri, 2011/11/11 - 7:17pm
You should put at least Thread.sleep(1) to avoid less-then-millisecond calls to the code returning the same number. Better yet, would be using locks and ensure thread-safety.
Peter ___ replied on Sun, 2011/11/13 - 11:24am
in response to:
Leen Toelen