DEVFYI - Developer Resource - FYI

What is the best way to generate a universally unique object ID? Do I need to use an external resource like a file or database, or can I do it all in memory?

JDBC Interview Questions and Answers


(Continued from previous question...)

What is the best way to generate a universally unique object ID? Do I need to use an external resource like a file or database, or can I do it all in memory?

1: Unique down to the millisecond. Digits 1-8 are are the hex encoded lower 32 bits of the System.currentTimeMillis() call.
2: Unique across a cluster. Digits 9-16 are the encoded representation of the 32 bit integer of the underlying IP address.
3: Unique down to the object in a JVM. Digits 17-24 are the hex representation of the call to System.identityHashCode(), which is guaranteed to return distinct integers for distinct objects within a JVM.
4: Unique within an object within a millisecond. Finally digits 25-32 represent a random 32 bit integer generated on every method call using the cryptographically strong java.security.SecureRandom class.

Answer1
There are two reasons to use the random number instead of incrementing your last. 1. The number would be predictable and, depending on what this is used for, you could be opening up a potential security issue. This is why ProcessIDs are randomized on some OSes (AIX for one). 2. You must synchronize on that counter to guarantee that your number isn't reused. Your random number generator need not be synchronized, (though its implementation may be).

Answer2
1) If ur using Oracle You can create a sequence ,by which you can generate unique primary key or universal primary key. 2) you can generate by using random nunmbers but you may have to check the range and check for unique id. ie random number generate 0.0 to 1.0 u may have to make some logic which suits ur unique id 3) Set the maximum value into an XML file and read that file at the time of loding ur application from xml . thanks and regards prasad

(Continued on next question...)

Other Interview Questions