Search code examples
javaweak-references

Are multiple weak references to the same object cleared in groups?


If I have multiple weak references pointing at the same object, and no strong references are around. Can I be sure both weak references are intact when one of them returns the object?


Solution

  • WeakReference wr1 = new WeakReference(objX);
    ...//somewhere else
    WeakReference wr2 = new WeakReference(objX);
    

    Now:

    1. If at a moment wr1.get() returns non-null, then wr2.get() will return non-null too.
    2. But wr1 and wr2 object themselves are gc-ed independently, their gs-paths are independent of each other and most importantly independent of objX.