Java Interview - strong references, soft references, weak references, phantom references What is the difference?

Strong references, soft references, weak references, phantom references What is the difference?

This pavement questions, are both vice and very high frequency of a topic, the need for good record it.

Different reference types, mainly reflected a different object accessibility (reachable) state and the impact on garbage collection

  • Strong references:

Our common coding such as: Object obj = new Object (); obj is a strong reference in ordinary objects created by the new keyword are strong references

As long as a strong reference point to an object, the object will be able to show there, the garbage collector will not touch such objects

For an ordinary object, if no other references to the relationship, as long as beyond the scope references or display the strong reference assigned to null, it can be garbage collected

  • Soft references

Soft references life cycle is shorter than the strong references

When the JVM think out of memory, it will go to try to recover the soft references to objects

If you think JVM memory free, temporary hold soft references

  • Weak references

Weak references of the life cycle is shorter than the soft references in the area of ​​process memory garbage collector thread scans under its jurisdiction, once the discovery of an object with weak references, regardless of the current memory space is insufficient, it can reclaim its memory

  • Phantom references

Phantom references are also called virtual reference

Phantom references cited by the weakest kind of relationship, if a phantom reference object holds only, and then it does not have any references, it may be recovered at any time, it is only a constructor and a get () method, and it's get () method just returns a null, that is to say will never be able to get the object referenced by virtual, virtual reference must be used with a reference queue and ReferenceQueue

Published 26 original articles · won praise 27 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_41170102/article/details/104695381