Object reference types of soft and weak references

  Mentioned weak references and soft references, think of dynamically allocated memory and memory recall. In the Java language, memory allocation and recovery of some areas are equipped with certainty (for example: the program counter, the virtual machine stack and native method stacks), they do not need too much to consider recycling issues; and memory allocation and some regions recovered are dynamic (for example, Java heap and method area, a plurality of interface implementation class memory needed may be different). Heap for garbage collector recovery point depends on the type of the reference object.

  Java There are four types of references:
  ① strong references (Strong Reference)
  throw OutOfMemoryError will not recover the object is associated with strong references.
  ② soft references (SoftReference)
  If an object has only soft references, enough memory space, the garbage collector does not reclaim it; if the memory space is insufficient (before the virtual machine throws an OutOfMemoryError), will reclaim the memory of these objects. As long as the garbage collector does not reclaim it, the object can be used by the program.
  Soft references are most often used to implement memory-sensitive cache.
  ③ weak reference (WeakReference)
  has only a weak reference objects have more short life cycle. Strength is weaker than some of the soft references, is associated with a weak reference to an object can only survive until the next garbage collection occurs, once discovered, regardless of the current memory space is sufficient or not, will reclaim its memory.
  For example: WeakHashMap class, it uses the key weak reference mode, i.e. based implementation with weak keys hash table Map. In a WeakHashMap, when a key is no longer in normal use, its entry will be automatically removed, it is possible to save storage space, can be used to cache data that have a non-exist.
  ④ virtual reference (the PhantomReference)
  useless.
  In short, the rational use of references can help the garbage collector.

Guess you like

Origin www.cnblogs.com/1693977889zz/p/11012797.html