[in depth understanding of Java virtual machine] characteristics of four reference types

Strong reference

The most common in Java is strong reference. Assigning an object to a reference variable is a strong reference. When an object is referenced by a strongly referenced variable, it is in reachable state. It cannot be recycled by the garbage collection mechanism. Even if the object will never be used in the future, the JVM will not recycle it. Therefore, strong references are one of the main causes of JAVA memory leaks.

Soft reference

Soft references need to be implemented with the softreference class. If an object has only soft references, it will not be recycled when the system memory is sufficient, and it will be recycled when the system memory space is insufficient.

Soft references can be used to implement memory sensitive caching.

A soft reference can be used in conjunction with a reference queue. If the object referenced by the soft reference is garbage collected, the virtual machine will add the soft reference to the associated reference queue.

Weak reference

Weak references need to be implemented with the WeakReference class. The difference between weak references and soft references is that weak references have a shorter lifetime than soft references. For objects with only weak references, as long as the garbage collection mechanism runs, the memory occupied by the object will always be recycled regardless of whether the memory space of the JVM is sufficient.

A weak reference can be used in conjunction with a reference queue. If the object referenced by the weak reference is garbage collected, the Java virtual machine will add the weak reference to the associated reference queue.

Virtual reference

Virtual reference needs to be implemented by phantomreference class. It cannot be used alone, but must be used in combination with reference queue. The main function of virtual reference is to track the state of the object being garbage collected.

When the garbage collector prepares to recycle an object, if it finds that it still has a virtual reference, it will add the virtual reference to the associated reference queue before recycling the memory of the object. The program can know 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 virtual reference has been added to the reference queue, it can take necessary actions before the memory of the referenced object is recycled.

Virtual reference needs to be implemented by phantomreference class. It cannot be used alone, but must be used in combination with reference queue. The main function of virtual reference is to track the state of the object being garbage collected.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>