Get a unique identifier

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 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 :

d578271282b42fce:-2955b56e:107df3fbc96:-8000
d578271282b42fce:-2955b56e:107df3fbc96:-7fff
d578271282b42fce:-2955b56e:107df3fbc96:-7ffe

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[]) {
    System.out.println(java.util.UUID.randomUUID());
    // output : dedc3f57-6ce1-4504-a92f-640d8d9d23c9
  }
 }

This is probably the preferred method.

Mini-FAQ on the subject : http://www.asciiarmor.com/post/33736615/java-util-uuid-mini-faq

Using Apache commons

If you need compatibility with 1.4 then the org.apache.commons.id.uuid 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();
 
  private static long nextId() {
    return nextId.getAndIncrement();
  }
}

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





If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2010
[ home ]