• Senior Software Engineer • Focused on Customers and Craftsmanship • Leader of the Phoenix Software Engineering Reading Group Mike is a DZone MVB and is not an employee of DZone and has posted 20 posts at DZone. You can read more from them at their website. View Full User Profile

Global unique identifiers in Java, the easy way

11.10.2011
| 13619 views |
  • submit to reddit

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/

Published at DZone with permission of Mike Christianson, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

Leen Toelen replied on Thu, 2011/11/10 - 3:26am

Take into account that UUID.randomUUID().toString() is not Threadsafe. A more scalable apporach is e.g. https://github.com/twitter/snowflake

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

// Number of milliseconds since 00:00:00 GMT Jan. 1, 1970. 

Calendar.getInstance(TimeZone.getDefault()).getTime().getTime(); 

 

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 Karussell replied on Sun, 2011/11/13 - 11:24am in response to: Leen Toelen

Hi Leen, would you mind to explain why this is not thead safe?

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.