Search code examples
javaweak-references

WeakReference and StrongReference GC behavior


I declared a strong reference-

Data data = new Data();

To make it eligible for garbage collection I made instance null-

data = null;

Now when I made reference null the object is not reachable and is garbage collected when GC runs.

And for using WeakReference-

Data data = new Data();
WeakReference<Data> weakRef = new WeakReference<Data>(data);

When I make reference variable null it will be eligible for garbage collection.

data = null;

When we use StrongReference we made its reference null to get it GC. In case of WeakRefernce also we need to make reference to object null to make it GC. What is difference between two. In case of Strong reference if we just make reference to object null it will eligible for GC and will be collected when GC runs.


Solution

  • If you have tangled objects (i.e. objcts that are not reachable anymore), the garbage collector is allowed to collect them and wipe them out. Note the wording: It is allowed. That means the garbage collector can decide not to collect them. In fact, it is not guaranteed that an object will be garbaged collected at all.

    The difference between objects managed by a SoftReference or a WeakReference and a removed strong reference is the garbage collection strategy:

    • Softly reachable objects will be collected if there is a need of memory.
    • Weakly reachable objects will be collected at the very first attempt.
    • Otherwise unreachable objects will be collected at the collector's strategy (which might be similar to softly reachable, and is also tunable with some JVM parameters at startup).

    Still, these are assumptions about the most probable strategy, but a garbage collector might decide in another way.

    Just a note: Weak and soft references do not make sense when being used in a local scope. They are most probably used in instance fields, and one must always take care of the fact that the referred-to object might already be collected.