Problem:
Before JDK1.2, objects had only "referenced" and "not referenced" states, and for some objects that were "useless now, but not sure if they were useful later", in such a scenario, they could only be defined as "not referenced" and therefore garbage collected.
Once the object is used in the future, the object cannot be found.
We want to describe a class of objects that are kept in memory if there is sufficient memory space, and if the memory after garbage collection is still very tight, the memory consumed by those objects is freed. (such as the caching function of the system)
4 Types of references:
Java introduced 4 types of references after 1.2: Strong references (strong Reference), soft references (Soft Reference), weak references (Weak Reference), virtual references (Phantom Reference). The strength of 4 references decreases in turn.
Strong reference: is a common reference, such as StringBuffer sb = new StringBuffer (), as long as a strong reference exists, it will not be garbage collected;
Soft Reference: as long as the memory space is sufficient, soft-referenced objects will not be released, and when the system will be a memory overflow, the soft-referenced objects will be included in the recycling scope, JDK1.2 using the SoftReference class to implement soft reference;
Weak references: weak references do not affect the life cycle of an object, and the garbage collector treats weakly referenced objects as normal objects (which can be recycled as long as there are no strong references); JDK1.2 uses the WeakReference class to implement weak references;
Virtual Reference: A virtual reference does not affect the life cycle of an object, the object instance cannot be obtained through a virtual reference, and the purpose of creating a virtual reference is to receive a system notification when the object is reclaimed by the garbage collector. JDK1.2 uses the Phantomreference class to implement virtual references.
Java reference types