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?

Alessandro A. Garbagnati

[I need to generate unique id's that will be used for node 'ID' attribute values within XML documents. This id must be unique system-wide. The generator must be available to a number of servlets that add various node structures to my XML docs as a service. What is the best way to tackle this? The 'possible' ways I can see:

  • Keep the maximum ID value in a flat-file where the service would read it upon start-up and increment it. Upon shutdown or failure, it would write the latest max id to the file.
  • Calculate the max id by searching the XML itself. This will be tougher since XML requires an alpha-numeric value (not strictly numeric).
  • Use a database (MySQL) with a two-field table where one field is the incremental counter.
I just have this feeling that none of the above are the most efficient ways of doing this.

Regards, -Andy]

There is an additional way to do that that doesn't rely on an external file (or database) like the one you have presentred. If has been presented in the EJB Design Patterns book, written by Floyd Marinescu, and available in a pdf format for free from the given link.

The suggested solution is based on the UUID for EJB pattern, that comes out from this question:

How can universally unique primary keys can be generated in menory without requiring a database or a singleton?

Without enetring in the specifics (you can fully check out the pattern by reading the appropriate chapter), the solution is to generate a 32 digit key, encoded in hexadecimal composed as follows:

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.

[See also the following FAQs:

- Alex Chaffee]