What are strong references, soft references, weak references, and phantom references in java

Reprinted here

Before jdk1.2, there were two kinds of citations, "already cited" and "unquoted". However, some phenomena cannot be described under certain specific circumstances. For example, some objects need to be discarded when memory is tight.
So after jdk1.2, references are divided into four types: strong references, soft references, weak references, and phantom references.
Here are the four kinds of references:

Strong citation

Strong quotation: In most cases we use, it is a strong quotation.
For example, Object o=new Object(); As long as o still points to the object object, the object object will not be recycled; as long as the strong reference exists, then the object pointed to by this reference will not be recycled. Even if the memory is insufficient, the jvm will only throw an exception. This reference will not be recycled. Only if we manually assign null, the jvm will reclaim the corresponding null.

Soft Reference (SoftReference):

If an object has a soft reference, if the memory is sufficient, the soft reference object will not be reclaimed. Then when the memory is insufficient, the soft reference object will be recycled. If after the soft reference is reclaimed, there is still not enough memory space, then an exception is thrown.

Weak Reference (WeakReference)

If an object has a weak reference, once the garbage collector starts scanning and finds the weak reference; then the object pointed to by the weak reference will be reclaimed, regardless of whether the memory is sufficient.

Phantom Reference (PhantomReference)

Phantom reference: In fact, it is very golden with the name, it is the same as no reference; it is used to track the activity of the object not being garbage collected; the virtual reference must be used in conjunction with the reference queue (ReferenceQueue). When the garbage collector is about to recycle an object, if it finds that it still has a phantom reference, it will add the phantom reference to the reference queue associated with it before reclaiming the object's memory. The program can determine whether the referenced object will be garbage collected by judging whether a virtual reference has been added to the reference queue. If the program finds that a phantom reference has been added to the reference queue, it can take necessary actions before the memory of the referenced object is reclaimed.

Note: Weak references and phantom references are rarely used in actual programming, and soft references are used more often. Soft references can speed up the JVM's recovery of garbage memory, maintain the operating safety of the system, and prevent problems such as out of memory (OutOfMemory).

Guess you like

Origin blog.csdn.net/weixin_43815275/article/details/114520651