For the garbage collection mechanism in Java, the standard of whether an object is reclaimed is whether the object is referenced. Therefore, references are also an important concept of the JVM's memory management.
References to objects in Java typically have the following 4 types:
1 Strong Reference 2 soft reference 3 weak reference 4 virtual reference
The usage and the difference are described below
1 Strong references: The most common in Java is a strong reference, which assigns an object to a reference variable, which is a strong reference. When an object is referenced by a strongly referenced variable, it is in a state of reach, it is not possible to be reclaimed by the garbage collection mechanism, even if the object will never be used to the JVM and will not be recycled. Therefore, a strong reference is one of the main causes of Java memory leaks.
2 Soft references: Soft references need to be implemented with the SoftReference class, and for objects with soft references, it is not recycled when the system memory is sufficient, and it is recycled when the system is running out of memory space. Soft references are typically used in memory-sensitive programs.
3 Weak references: Weak references need to be implemented with the WeakReference class, which is shorter than the lifetime of a soft reference, and for objects that have only a weak reference, the memory used by the object is recycled whenever the garbage collection mechanism runs, regardless of whether the JVM's memory space is sufficient.
4 Virtual Reference: The virtual reference needs to be implemented by the Phantomreference class, which cannot be used alone and must be used in conjunction with the reference queue. The primary function of a virtual reference is to track the state of the object being garbage collected.
Four types of references in Java, strong references, soft references, weak references, virtual references