Interface UniqueId


public interface UniqueId
An interface for objects that have a unique ID (unique identifier). If you are tempted to print the value of System.identityHashCode(), consider using this instead.

Using System.identityHashCode is not a unique identifier, because two values can have the same identityHashCode if they are allocated into the same location in memory. Garbage collection can move or reclaim the first value, permitting the second value to be allocated exactly where the first one was.

To use the UniqueId interface, add implements UniqueId to your class definition and drop in the following code snippet.


 /** The unique ID for the next-created object. */
 private static final AtomicLong nextUid = new AtomicLong(0);
 /** The unique ID of this object. */
 private final transient long uid = nextUid.getAndIncrement();
 @Override
 public long getUid() {
   return uid;
 }
 
You can also use the above code to implement a unique identifier, without subtyping the UniqueId interface.

If you need a unique identifier for a class that you cannot edit (that is, you cannot make it implement UniqueId), use UniqueIdMap.

  • Method Summary

    Modifier and Type
    Method
    Description
    default String
    Returns the simple name of the class and the unique ID of this object.
    long
    Returns the unique ID of this object.
  • Method Details

    • getUid

      long getUid(@UnknownInitialization(UniqueId.class) UniqueId this)
      Returns the unique ID of this object.
      Returns:
      the unique ID of this object
    • getClassAndUid

      default String getClassAndUid(@UnknownInitialization(UniqueId.class) UniqueId this)
      Returns the simple name of the class and the unique ID of this object. This method is intended for use in diagnostic output.
      Returns:
      the simple name of the class and the unique ID of this object