Let’s start with code.
Future<MyResult> obj = getFuture();
debugLog.println("Handling future: " + System.identityHashCode(obj);
and then somewhere else same again, or possibly the same piece of code executed again, possibly in different thread.
Future<MyResult> obj = getFuture();
debugLog.println("Handling future: " + System.identityHashCode(obj);
Now above, if obj’s are same object, the debug prints will be same, obviously. But if they are different, there’s still a chance of hash collision, so the printout may be same even for different objects. So having same output (or more generally, same string) does not guarantee same object.
Question: Is there a way in Java to get unique id string for arbitrary object? Or more formally, give static String Id.str(Object o) method so that so that this is always true:
final Object obj1 = ...;
final String firstId = Id.str(obj1);
// arbitrary time passes, garbage collections happen etc.
// firstId and obj1 are same variables as above
(firstId.equals(Id.str.obj2)) == (obj1 == obj2)
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 thishashCodeis 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()?