Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Global unique identifiers in Java, the easy way

DZone's Guide to

Global unique identifiers in Java, the easy way

· Java Zone
Free Resource

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

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/

Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}