Strong references, soft references, weak references, virtual references: Different reference types are mainly represented on the GC
-
Strong reference: If an object has a strong reference, it will not be reclaimed by the garbage collector. Even if there is not enough memory space, the JVM does not reclaim it, but instead throws a outofmemoryerror error that causes the program to terminate unexpectedly. If you want to break the association between a strong reference and an object, you can explicitly assign a reference to NULL, so that the JVM reclaims the object at the appropriate time
-
Soft references: When using soft references, if there is enough memory space, soft references can continue to be used without being reclaimed by the garbage collector, and soft references are reclaimed by the garbage collector only when there is insufficient memory.
-
Weak reference: An object with a weak reference has a more ephemeral life cycle. Because when the JVM is garbage collected, weak references are recycled whenever a weak reference object is found, regardless of whether the current memory space is sufficient. However, because the garbage collector is a low-priority thread, it is not always possible to quickly discover weak reference objects
-
Virtual reference: As the name implies, is the form of a dummy, if an object only holds a virtual reference, then it is equivalent to no reference, at any time may be reclaimed by the garbage collector.
What is the difference between WeakReference and softreference?
This is explained in four reference types, which can be described briefly: although WeakReference and SoftReference both contribute to the efficiency of GC and memory, WeakReference, once the last strong reference is lost, is recycled by GC, and the soft References, although not prevented from being recycled, can be deferred until the JVM is running out of memory.
Four types of references in Java