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.
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);
}
}
I want the above codes to work when the method is called by multiple threads.
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?
How about having a synchronized block but without the volatile keyword?
Thanks in advance.
ADDED:
If I changed to below codes, would the volatile keyword still required?
public class Util {
private static volatile String uniqueID;
public static synchronized String generateUniqueID() {
uniqueID = UUID.randomUUID().toString();
return uniqueID;
}
}