title: Generating a globally unique identifier in Java
body: <p><strong>Summary:</strong> I'm developing a persistent Java web application, and I need to make sure that all resources I persist have globally unique identifiers to prevent duplicates.</p>
  
  <p><strong>The Fine Print:</strong></p>
  
  <ol>
  <li>I'm not using an RDBMS, so I don't have any fancy sequence generators (such as the one provided by Oracle)</li>
  <li>I'd like it to be fast, preferably all in memory - I'd rather not have to open up a file and increment some value</li>
  <li>It needs to be thread safe (I'm anticipating that only one JVM at a time will need to generate IDs)</li>
  <li>There needs to be consistency across instantiations of the JVM.  If the server shuts down and starts up, the ID generator shouldn't re-generate the same IDs it generated in previous instantiations (or at least the chance has to be really, really slim - I anticipate many millions of presisted resources)</li>
  <li>I have seen the examples in the EJB unique ID pattern article.  They won't work for me (I'd rather not rely solely on System.currentTimeMillis() because we'll be persisting multiple resources per millisecond).</li>
  <li>I have looked at the answers proposed in <a href="https://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string-in-java">this question</a>.  My concern about them is, what is the chance that I will get a duplicate ID over time?  I'm intrigued by the suggestion to use <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/UUID.html" rel="nofollow noreferrer">java.util.UUID</a> for a <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier" rel="nofollow noreferrer">UUID</a>, but again, the chances of a duplicate need to be infinitesimally small.</li>
  <li>I'm using JDK6</li>
  </ol>