What are the chances of getting exactly the same object reference twice

java

Solution

(I'm answering what I think what you really wanted to know, rather than the particular snippet you have)

It's implementation dependant. The contract of object reference is that as long as the object is still alive, no other object will compare == with it. This implies that after the object is garbage collected, the VM is free to reuse the same object reference.

Implementation of Java may choose to use an increasing integer for object reference, in which case you can only get the same object reference when the reference counter overflows back to 0. Other implementation may use memory location, which makes it more likely for the same reference to be reused. In any case, you should define your own object identity if that matters.

Problem

I sometimes assume that if `oldObject != newObject` then the object has changed - which seems a fair assumption in most cases but is it truly a bad assumption? In short, under what situation could the following code print "Same!"? ``` static WeakReference<Object> oldO = null; ... Object o = new Object(); oldO = new WeakReference(o); // Do some stuff with o - could take hours or even days to complete. ... // Discard o (or let it go out of scope). o = null; // More stuff - could be hours or days later. ... o = new Object(); // Later still. if ( o == oldO.get() ) { System.out.println("Same!"); } ``` I realise that this is indeed remotely possible because an object reference is essentially the memory address of the object (or could be in some JVM). But how likely is it? Are we talking decades of run-time before it actually happens? Added My apologies - please assume that `oldO` is some form of `weak` reference that does not stop it from being collected. Perhaps it is `Weak` as the code (now) suggests or the reference is store in a database or a file somewhere.

Original source