There are 4 levels of references in Java: strong references, soft references, weak references, and virtual References. In addition to strong references, the other 3 references can find the corresponding class in the Java.lang.ref package. Developers can use them directly in the application, where finalreference means "final" references, which implement the Object's finalize () method.
1 Strong references
A strong reference is a generic reference type used in a program, and a strongly referenced object is accessible and not recycled. In contrast, soft references, weak references, and virtual references are soft-accessible, weakly-accessible, and virtual-accessible, and can be recycled under certain conditions.
Strong reference example: StringBuffer sb = new StringBuffer ("Hello world");
Assuming that the above code is running in the function body, the local variable SB is allocated on the stack, and the object StringBuffer instance is allocated on the HEAP. The local variable SB points to the heap space of the StringBuffer instance, and with SB you can manipulate the instance, then SB is a strong reference to the StringBuffer instance.
Features of strong references:
- Strong references direct access to target objects
- The object that the strong reference points to is not reclaimed by the system at any time, and the virtual machine prefers to throw an oom exception and not to reclaim the object that the strong reference refers to.
- A strong reference can cause a memory leak
2 References----soft references that can be recycled
A soft reference is a reference type that is weaker than a strong reference, and an object holds only soft references, and when heap space is low, it is reclaimed. Soft references use the Java.lang.ref.SoftReference type
Characteristics:
GC does not necessarily reclaim soft-referenced objects, but when memory resources are strained, soft-referenced objects are recycled, so soft-referencing objects do not cause memory overflow.
3 Weak references-----discovery is recycled
4 Virtual REFERENCE----OBJECT Recycle tracking
An object that holds a virtual reference is almost the same as no reference.
Its role is mainly to track the garbage collection process
Four types of Java references soft and weak