Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing unique object identity for debugging purposes in Java

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)
like image 851
hyde Avatar asked Jan 24 '13 11:01

hyde


People also ask

How do you print an object in java?

The print(Object) method of PrintStream Class in Java is used to print the specified Object on the stream. This Object is taken as a parameter. Parameters: This method accepts a mandatory parameter object which is the Object to be printed in the Stream. Return Value: This method do not returns any value.

How do you make an object unique in java?

Create Employee object. Notice I have override equals() and hasCode() method through which I am making Employee object unique based on attributes – name and address . Create HashSet test class to test the uniqueness of objects added to the HashSet.


1 Answers

I think, that actually there isn't any method (i.e. technique) which will guarantee you such uniqueness of the object's ID. The only purpose of such identification is a method for addressing to 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 system to use its former address space for placing new a object's data.

But in fact during some short period among all available objects which have any references inside your program, System.identityHashCode(obj) will actually give you 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 not guaranteed for foreign JVMs.

Also, you can read this famous QA: Java: How to get the unique ID of an object which overrides hashCode()?

like image 143
Andremoniy Avatar answered Sep 30 '22 14:09

Andremoniy