Printing unique object identity for debugging purposes in Java
I think actually there isn't any method (i.e. technique) which will guarantee you such a uniqueness of the object's ID. The only purpose of such an identification is to have a method for addressing this object's data in memory. In case when this object dies and then is removed from the memory by the GC, nobody will restrict the system to use its former address space for placing new object's data.
But in fact during some short period of time, among all available objects which have any references inside your program, System.identityHashCode(obj)
will actually give you a unique identity of the object. This is because this hashCode
is calculated using the object's in-memory location. However, it is an implementation feature, which is not documented and is not guaranteed for other JVMs.
Also, you can read this famous QA: Java: How to get the unique ID of an object which overrides hashCode()?