The difference between strong reference, soft reference, weak reference and phantom reference-Java

Why do we define four reference types, strong reference, soft reference, weak reference, and phantom reference in Java?

Our definition of an object cannot be limited to the two states of "referenced" and "unreferenced", because we still have several reference types that can describe such a type of object: when the memory space is still sufficient, it remains in the memory If the memory space is still very tight after garbage collection, then these objects can be discarded (this type of object is used in the caching function of many systems).

After the JDK 1.2 version, Java expanded the concept of references, dividing references into four types: Strongly Re-ference, Soft Reference, Weak Reference, and Phantom Reference. The intensity of these four citations gradually weakened.

The purpose of defining these four reference types:

1. Let the programmer determine the life cycle of certain objects through code;
2. It is conducive to the JVM for garbage collection.

Strong reference: It is indispensable and will not be recycled by the garbage collector.

When the memory space is insufficient, the program would rather throw a java.lang.OutOfMemoryError error, so that the program terminates abnormally, and does not reclaim such objects.

 public static void main(String[] args) {
    
    
        Object[] objects=new Object[Integer.MAX_VALUE];  
    }
"C:\Program Files\Java\jdk1.8.0_192\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2020.1.3\lib\idea_rt.jar=6744:C:\Program Files\JetBrains\IntelliJ IDEA 2020.1.3\bin" ...Day27.TestDemo
Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit
	at Day27.TestDemo.main(TestDemo.java:5)

Process finished with exit code 1

If you want to break the connection between a strong reference and an object, you can explicitly assign the reference to null, so that the JVM will reclaim the object at an appropriate time.

Soft references: useful but not necessary objects.

The SoftReference class is
only used to refer to objects associated with soft references. Before a memory overflow exception occurs in the system, these objects will be listed in the recovery range for a second recovery. If there is not enough memory in this recovery, it will be thrown. Memory overflow is abnormal. Only when the memory space is insufficient, the Java virtual machine will reclaim the object, such as the soft references used by some web page caches and image caches.

public static void main(String[] args) throws InterruptedException {
    
    
        //创建方式
        Object obj = new Object();
        SoftReference<Object> sf = new SoftReference<Object>(obj);
        //使用方式
        Object obj1 = sf.get();
        //说明没有被回收
        if(obj1 != null) obj1.wait();//使用对象

    }

Weak references: non-essential objects.

WeakReference class
Objects associated with weak references can only survive until the next garbage collection occurs. When the next garbage collection occurs, regardless of whether the JVM memory space is sufficient, the objects associated with weak references will be reclaimed.

The difference between weak reference and soft reference:
different life cycle: weakly referenced objects have a shorter life cycle. In the process of scanning the memory area under its jurisdiction by the garbage collector, once an object with weak reference is found, regardless of the current memory Whether it is enough, it will be recycled. The garbage collector is a thread with a very low priority, so objects that only have weak references may not be found, so objects associated with soft references will only be recycled when there is insufficient memory space, while those associated with weak references Objects are always collected when the JVM is garbage collected.

Phantom reference: the weakest kind of reference, just like a virtual reference

Whether an object has a phantom reference will not affect its lifetime at all, and it is impossible to obtain an object instance through a phantom reference. The sole purpose of setting a phantom reference association for an object is to receive a system notification when the object is reclaimed by the collector.
PhantomReference class

to sum up:

Reference type Time to be garbage collected use Survival time
Strong citation Never General state of the object Terminate when the JVM stops running
Soft reference When memory is low Object cache Terminate when memory is insufficient
Weak reference During garbage collection Object cache Terminate after GC runs
Phantom reference unknown Receive a system notification when this object is collected by the collector unknown

Strong references:
Objects that will not be recycled.
Soft reference:
If the memory of the weakly referenced object is reclaimed, the memory still alarms, continue to reclaim the soft reference object.
Weak reference:
If the memory is still alarmed after the phantom referenced object is reclaimed, continue to reclaim the weakly referenced object
.
Phantom reference: The memory of the virtual machine is not enough. The alarm is started, and the garbage collection mechanism starts to execute System.gc(); if no objects are collected, the objects without phantom references are collected

Guess you like

Origin blog.csdn.net/m0_46551861/article/details/115260635