java.lang.ref.SoftReference Class in Java
When we create an object in Java, an object isn’t soft by default. To create a Soft Reference Object, we must explicitly specify this to the JVM. In Soft reference, even if the object is free for garbage collection then also it’s not garbage collected until JVM is in need of memory badly. The objects get cleared from the memory when JVM runs out of memory.
Why Soft Reference Objects are used?
When a soft reference object is created, it is marked for garbage collection. However, it is not garbage collected until and unless there is a deficiency of memory in the JVM.
Constructors in the SoftReference Class :
|SoftReference ( T referent)||Creates a new soft reference that refers to the given object.|
|SoftReference ( T referent, ReferenceQueue <T> q)||Creates a new soft reference that refers to the given object and is registered with the given queue.|
-> Calling Display Function using strong object: Display Function invoked ... -> Object set to null -> Calling Display Function after retrieving from soft Object Display Function invoked ...
Example Showing enqueue() and isEnqueued() method of SoftReference Class:
-> Retrieving object from Soft Reference using get () show () from X invoked.. -> Is it possible to queue object using enqueue () false -> Checking if reference is queued using isEnqueued () false
-> Retreiving object from Soft Reference using get () show () from X invoked.. -> Is it possible to queue object using enqueue () false -> Checking if reference is queued using isEnqueued () false
Methods inherited from Reference Class: Method Description
Method Name clear () Clears this reference object. enqueue () Adds this reference object to the queue with which it is registered, if any. get () Returns this reference object’s referent. isEqueued () Tells whether this reference object has been enqueued, either by the program or by the garbage collector.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.