java.lang.ref.SoftReference class is used to create an object that wraps another object - innerObject. The object it wraps can be removed from memory by Garbage Collector (GC) if it is no longer being used somewhere else stronger than GC and the system is in need of more memory.
The object is wrapped inside a WeakReference that acts like a diner in a restaurant. When diners finish eating, they are ready to leave the table even if at that time the restaurant has many empty tables. SoftReference is a bit different from WeakReference, diners can sit back and only leave if the restaurant has no more free tables or the number of available free tables is less than a safe value.
Basically, it's a bit more difficult to give an example of SoftReference and show you firsthand how Garbage Collector removes soft references from memory, since we need to simulate near-full memory situation. If the simulation is not perfect we will overflow the memory. Although before OutOfMemoryError was thrown, soft references were removed from memory.
Advice: WeakReference should be learned before continuing with SoftReference:
When an object is removed from memory, its finalize() method is called. Note: This method has been marked as deprecated since Java 9, but we can still use it just to print a message.
The example below shows that GC will remove soft references from memory to avoid throwing an OutOfMemoryError.
Java allows you to configure when GC should remove soft references from memory.
The default value of SoftRefLRUPolicyMSPerMB parameter is 1000 Milliseconds. This means that if only 10MB of HEAP memory is available, GC will work to remove soft references that have been unused for longer than 1000 milliseconds.
Java documentation says that:
"All soft references to softly-reachable objects are guaranteed to have been freed before the virtual machine throws an OutOfMemoryError."
Apparently the above is only really true when "-XX:SoftRefLRUPolicyMSPerMB=0".
Another better example. Let's try to simulate a situation where Java's memory is near exhaustion:
All methods of SoftReference are inherited from the parent class.
2- SoftReference(T, ReferenceQueue<? super T>
Create a SoftReference object that wraps innerObject object. When innerObject is removed from memory by GC, this SoftReference object will be added to the queue.
Sometimes SoftReference is also used in a simple cache system, where the data rarely changes. Java virtual machine automatically removes these data when it needs more memory.
Example: A cache system stores data of image files.