Strong, weak, reference phantom reference

Author: winterSunshine
link: https: //www.zhihu.com/question/37401125/answer/100981172
Source: know almost
copyrighted by the author. Commercial reprint please contact the author authorized, non-commercial reprint please indicate the source.

1. Explain the concept
    • Strong reference is the most commonly used reference: Object o = new Object () ; characteristics: GC will not be
      • The object references explicitly set to null: o = null; // help recover garbage collector object
      • Examples ArrayList of source code:

    • Soft references are used to describe some but not necessarily well as with objects in Java using java.lang.ref.SoftReference classes to represent. For soft references associated with the object, JVM will only recover the object in the memory of the time. Therefore, it can well be used to solve problems OOM, and this feature is ideal for implementing cache: such as page caching, caching pictures.
      1. Browser page cache instances:
      2. Soft references can be a reference queue (ReferenceQueue) used in combination, if the soft reference object referenced by the garbage collector, Java virtual machine will be added to this soft references cited associated queue.

  • Weak references the difference between a soft reference that: only a weak reference objects have more short life cycle. In the process of the garbage collector thread scans memory area under its jurisdiction, once the objects found only a weak reference, regardless of the current memory space is sufficient or not, will reclaim its memory. However, the garbage collector is a low priority thread, and therefore will not necessarily quickly find objects that have only a weak reference.
If the object is occasional use, and you always will be able to use to get in, but do not want to affect garbage collection for this object, then you should use Weak Reference to remember this object.
  1. Example:

  • Virtual reference , also known as phantom references: the presence of an object is referenced has a virtual lifetime will not have an impact in the real can not be obtained for a reference to the object through the virtual reference. Only use: The system can receive notification object is GC, JAVA implemented with virtual reference PhantomReference.
2. compare different:

Guess you like

Origin www.cnblogs.com/yngjian/p/12059428.html