There are four reference types in Java: strong reference, soft reference, weak reference, and phantom reference ).
I. Interpretation of the four reference types:
- JVM holds general objects until they are no longer reachable. In other words, when no valid reference points to them, it will be reclaimed, and invalid reference will not be included.
- Objects that soft references point to will be garbage collected if there is no reference pointing to them and the memory space is insufficient. In most cases, it is used to implement memory-sensitive cache. If there is no GC time limit, it will be cleared before OOM occurs.
- Objects pointed to by weak references are immediately spam when no references point to them. If an object only has weak references, this object cannot be touched. These objects will be garbage collected at any time and will be discarded in the next GC cycle.
- Virtual references point to objects that have executed the Finalize method but have not recycled the memory.
Ii. Comparison of the four reference types:
| Type |
Purpose |
Function |
GC condition triggering |
Implementation class |
| Strong reference |
Common reference types, as long as the object references are strongly referenced, they will not be garbage collected |
Normal reference |
Any object that is not strongly referenced can be collected by garbage collection. |
Default type |
| Soft reference |
When the memory is sufficient, the object will not be garbage collected. |
To ensure that the object will not be garbage collected even if there is no reference pointing to it, prevent reference pointing to this object again |
After the first GC, the JVM needs to reclaim more space. |
Java. Lang. Ref. softreference |
| Weak reference |
Objects that can be reached are not collected by garbage collection. |
If the object is no longer referenced, it will be automatically recycled. |
After GC, the object only has weak references. |
Java. Lang. Ref. weakreference Java. util. weakhashmap |
| Virtual Reference |
This allows you to clear objects that have executed the Finalize method but have not recycled the memory. |
Special cleanup |
After the Finalize method is executed |
Java. Lang. Ref. phantomreference |