Weak and soft reference differences in Java

March 21, 2017

The main difference between WeakReference and SoftReference is the moment of removal by a garbage collector.

1. WeakReference

WeakReference objects are always released when garbage collector reclaim.

The output of the above code always be:

2. SoftReference

As long as your program has a lot of unused memory, soft references will be kept in memory.

In above example, we don’t use all memory, so garbage collector doesn’t release softString.

SoftRefernece is good for a cache. When a program needs more memory SoftReference object will be removed.

Click here to add a comment

Leave a comment: