Any object which has an active strong reference are not eligible for garbage collection. The object is garbage collected only when the variable which was strongly referenced points to null.
public class StrongReferenceUsage {
@Test
public void stringReference(){
//obj is strong reference
Object obj = new Object();
}
}
The objects gets cleared from the memory when JVM runs out of memory.
@Test
public void softReference(){
Object obj = new Object();
SoftReference<Object> soft = new SoftReference<>(obj);
obj = null;
log.info("{}",soft.get());
System.gc();
log.info("{}",soft.get());
}
22:50:43.733 [main] INFO com.flydean.SoftReferenceUsage - java.lang.Object@71bc1ae4
22:50:43.749 [main] INFO com.flydean.SoftReferenceUsage - java.lang.Object@71bc1ae4
Two constructors
public SoftReference(T referent)
public SoftReference(T referent, ReferenceQueue<? super T> q)
If JVM detects an object with only weak references, this object will be marked for garbage collection.
@Test
public void weakReference() throws InterruptedException {
Object obj = new Object();
WeakReference<Object> weak = new WeakReference<>(obj);
obj = null;
log.info("{}",weak.get());
System.gc();
log.info("{}",weak.get());
}
22:58:02.019 [main] INFO com.flydean.WeakReferenceUsage - java.lang.Object@71bc1ae4
22:58:02.047 [main] INFO com.flydean.WeakReferenceUsage - null
Two constructors
public WeakReference(T referent);
public WeakReference(T referent, ReferenceQueue<? super T> q);
*The objects are **eligible for garbage collection, but before removing them from the memory, JVM puts them in a queue called ReferenceQueue.
@Slf4j
public class PhantomReferenceUsage {
@Test
public void usePhantomReference(){
ReferenceQueue<Object> rq = new ReferenceQueue<>();
Object obj = new Object();
PhantomReference<Object> phantomReference = new PhantomReference<>(obj,rq);
obj = null;
log.info("{}",phantomReference.get());
System.gc();
Reference<Object> r = (Reference<Object>)rq.poll();
log.info("{}",r);
}
}
07:06:46.336 [main] INFO com.flydean.PhantomReferenceUsage - null
07:06:46.353 [main] INFO com.flydean.PhantomReferenceUsage - java.lang.ref.PhantomReference@136432db
ReferenceQueue, GC will put the Reference of the object to be recycled into ReferenceQueue, and the Reference needs to be handled by the programmer(call the poll method).