Get a unique identifierTag(s): String/Number Thread Varia

Using java.rmi.dgc.VMID
java.rmi.dgc.VMID can generate an identifier. Each new VMID is unique for all Java virtual machines under the following conditions:
  • The conditions for uniqueness for objects of the class java.rmi.server.UID are satisfied
    • An independently generated UID instance is unique over time with respect to the host it is generated on as long as the host requires more than one millisecond to reboot and its system clock is never set backward. A globally unique identifier can be constructed by pairing a UID instance with a unique host identifier, such as an IP address.
  • An address can be obtained for this host that is unique and constant for the lifetime of this object.

The format is :

[2 chars for each byte in 4 byte ip address]:
  [8 char unique string]:
    [16 char from time in hex]:
      [8 char from count]

Code :

public class TestVMID {
 public static void main(String arg[]) {
   System.out.println(new java.rmi.dgc.VMID().toString());
   System.out.println(new java.rmi.dgc.VMID().toString());
   System.out.println(new java.rmi.dgc.VMID().toString());

Output :

Using java.util.UUID
In 1.5, you have java.util.UUID which is less esotoric.
public class TestUUID {
  public static void main(String arg[]) {
    // output : dedc3f57-6ce1-4504-a92f-640d8d9d23c9

This is probably the preferred method.

Mini-FAQ on the subject :

Using Apache commons
If you need compatibility with 1.4 then the is an option.
Using java.util.concurrent.AtomicLong
A simple numerical id, start at zero and increment by one.
import java.util.concurrent.AtomicLong;

public class Descriptor {
  private static final AtomicLong nextId = new AtomicLong();

  public static long nextId() {
    return nextId.getAndIncrement();

See also this HowTo for unique numerical id based on the system time.

blog comments powered by Disqus