title: Java volatile and/or synchronized
body: <p>I have a static method that is supposed to generate a unique ID based on the current timestamp as shown in the codes below. To ensure that the newly generated ID is not the same as the previously generated ID (due to very fast computer such that the millisecond does not change), I put in a loop to compare the newly generated ID against the previously generated one. If they are the same, it will generate another ID.</p>
  
  <pre><code>public class Util {
  
      protected static String uniqueID;
  
      public static String generateUniqueID() {
          SimpleDateFormat timstampFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
          do {
              String timestamp = timstampFormat.format(new Date());
              if (!timestamp.equals(uniqueID)) {
                  uniqueID = timestamp;
                  return uniqueID;
              }
          } while (true);
      }
  
  }
  </code></pre>
  
  <p>I want the above codes to work when the method is called by multiple threads.</p>
  
  <p>If I merely put the volatile keyword to the uniqueID variable, would that be good enough? Do I still need to have a synchronized block?</p>
  
  <p>How about having a synchronized block but without the volatile keyword?</p>
  
  <p>Thanks in advance.</p>
  
  <p><strong>ADDED:</strong></p>
  
  <p>If I changed to below codes, would the volatile keyword still required?</p>
  
  <pre><code>public class Util {
  
      private static volatile String uniqueID;
  
      public static synchronized String generateUniqueID() {
          uniqueID = UUID.randomUUID().toString();
          return uniqueID;
      }
  
  }
  </code></pre>