Search code examples
referencegarbage-collectionjvmweak-referencesrecover

Recovering hard refs from soft/weak references


In my program, situations may occur when object is available only over weak references. I have noticed some NullPointerExceptions, which are not easy to debug. I wonder, is it possible that once object been marked as weakly reachable becomes normally hard again when user thread executes its methods or reaches through hard references. The various forums over internet say that we can recover hard references, given soft/weak but I wonder why is SPEC is so specific then

Reachability

Going from strongest to weakest, the different levels of reachability reflect the life cycle of an object. They are operationally defined as follows: An object is strongly reachable if ... An object is softly reachable if ... An object is weakly reachable ...

Shouldn't I read lifecycle as unidirectional waterfall model? Can one object appear in WeakRefQueue multiple times if it is recovered while being weak for some time? I used weak refs to recover hard references when object is requested by ID but also put them into ref queue to determine if the object is still in use by clients and do some cleanup if not. This is all done in one thread but I ask myself if this can create any problems.


Solution

  • An object is strongly referenced if it can be accessed via strong references. There is nothing more magical than that. This means an object can have multiple strong references, multiple soft reference and multiple weak references, or any combination.

    The only distinction is that a reference via a WeakReference doesn't count as a strong reference. If the reference is still available you can get a strong reference from a weak reference like this.

    WeakReference<MyType> ref = ...
    MyType stringRef = ref.get();
    

    All this does is copy the reference, nothing else need happen.