Talking about the difference between strong reference, soft reference, weak reference and phantom reference


Preface

Understanding the reference relationship is mainly to better understand the garbage collection mechanism, the life cycle of the underlying object, and it will be very helpful for us to design a reliable cache and other frameworks, or to diagnose problems such as OOM applications. For example, to diagnose the memory leak of the MySQL connector-j driver in a specific mode (useCompression=true), we need to understand how to troubleshoot the accumulation of phantom references.
.


Tip: The following is the content of this article, the following cases are for reference

1. Four definitions of references

1. Strong references

Any object with active strong references is not eligible for garbage collection. When an object is garbage collected, it will be collected as garbage only when the strong reference point is an empty variable.

MyClass obj = new MyClass ();      
obj = null;
//'obj' object is no longer referencing to the instance. 
So the 'MyClass type object is now available for garbage collection.  
// Java program to illustrate Strong reference 
class Gfg 
{ 
    //Code.. 
} 
public class Example 
{ 
    public static void main(String[] args) 
    { 
         //Strong Reference - by default 
        Gfg g = new Gfg();     
          
        //Now, object to which 'g' was pointing earlier is  
        //eligible for garbage collection. 
        g = null;  
    } 
}  

Insert picture description here

2. Soft references

In soft references, objects can be exempted from some garbage collection until the JVM urgently needs memory. When the JVM runs out of memory, these objects will be cleared from memory.

3. Weak references

Weak reference (WeakReference) does not make the object exempt from garbage collection, but only provides a way to access the object in the weak reference state. This can be used to construct a relationship without specific constraints, for example, to maintain a non-mandatory mapping relationship, if the object is still there when trying to obtain it, use it, otherwise re-implementation. It is also the choice of many cache implementations

//Code to illustrate Soft reference 
import java.lang.ref.SoftReference; 
class Gfg 
{ 
    //code.. 
    public void x() 
    { 
        System.out.println("GeeksforGeeks"); 
    } 
} 
  
public class Example 
{ 
    public static void main(String[] args) 
    { 
        // Strong Reference 
        Gfg g = new Gfg();      
        g.x(); 
          
        // Creating Soft Reference to Gfg-type object to which 'g'  
        // is also pointing. 
        SoftReference<Gfg> softref = new SoftReference<Gfg>(g); 
          
        // Now, Gfg-type object to which 'g' was pointing 
        // earlier is available for garbage collection. 
        g = null;  
          
        // You can retrieve back the object which 
        // has been weakly referenced. 
        // It successfully calls the method. 
        g = softref.get();  
          
        g.x(); 
    } 
} 

Insert picture description here

4. Phantom (virtual reference)

Objects referenced by phantom references are eligible for garbage collection. However, before deleting them from memory, the JVM puts them in a queue called a'reference queue'. After calling the finalize() method, they are put into the reference queue.

//Code to illustrate Phantom reference 
import java.lang.ref.*; 
class Gfg 
{ 
    //code 
    public void x() 
    { 
        System.out.println("GeeksforGeeks"); 
    } 
} 
  
public class Example 
{ 
    public static void main(String[] args) 
    { 
        //Strong Reference 
        Gfg g = new Gfg();      
        g.x(); 
          
        //Creating reference queue 
        ReferenceQueue<Gfg> refQueue = new ReferenceQueue<Gfg>(); 
  
        //Creating Phantom Reference to Gfg-type object to which 'g'  
        //is also pointing. 
        PhantomReference<Gfg> phantomRef = null; 
          
        phantomRef = new PhantomReference<Gfg>(g,refQueue); 
          
        //Now, Gfg-type object to which 'g' was pointing 
        //earlier is available for garbage collection. 
        //But, this object is kept in 'refQueue' before  
        //removing it from the memory. 
        g = null;  
          
        //It always returns null.  
        g = phantomRef.get();  
          
        //It shows NullPointerException. 
        g.x(); 
    } 
} 
<font color=#999AAA >
Exception in thread "main" java.lang.NullPointerException
    at Example.main(Example.java:31)

output

GeeksforGeeks

Two, expansion

1. Analysis of object reachability status circulation

Strongly reachable (Strongly Reachable) is when an object can be accessed by one or more threads without using various references. For example, if we newly create an object, the thread that created it is strongly reachable to it.

Softly reachable (Softly Reachable) is when we can only access the state of an object through soft references.

Weakly reachable (Weakly Reachable), similar to the aforementioned, is the state when it cannot be accessed through strong or soft references, but only through weak references. This is very close to the time of the finalize state. When the weak reference is cleared, it meets the conditions of finalize.

Phantom Reachable. The above flowchart is very intuitive, that is, there is no strong, soft, or weak reference association, and finalize has passed, only when the phantom reference points to this object.

Of course, there is one final state, unreachable, which means that the object can be cleared.

Judging the reachability of an object is part of the consideration of the JVM garbage collector deciding how to handle the object.

to sum up

1 Understand the definition 2 When is the opportunity to recycle

Guess you like

Origin blog.csdn.net/aa327056812/article/details/109483298