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 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.
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).