Four kinds of references of Java-strong and weak

1. Strong reference:

  If an object has a strong reference, it will not be collected by the garbage collector. Even if the current memory space is insufficient, the JVM will not reclaim it, but throw an OutOfMemoryError error, causing the program to terminate abnormally. If you want to break the association between a strong reference and an object, you can explicitly assign the reference to null, so that the JVM will recycle the object at the appropriate time

Object obj = new Object (); // As long as obj still points to the Object object, the Object object will not be recycled 
obj = null ;   // Manually set null

2. Soft reference:

  When using soft references, if the memory space is sufficient, the soft references can continue to be used without being collected by the garbage collector. Only when the memory is insufficient, the soft references will be collected by the garbage collector. When the memory is sufficient, the soft reference object will not be reclaimed. Only when the memory is insufficient, the system will reclaim the soft reference object. If there is still insufficient memory after the soft reference object is reclaimed, the memory overflow exception will be thrown. This feature is often used to implement caching technologies, such as web page caching, image caching, and so on.
3. Weak reference:

  Objects with weak references have a shorter life cycle. Because when the JVM performs garbage collection, once a weak reference object is found, regardless of whether the current memory space is sufficient, the weak reference will be recycled. However, because the garbage collector is a lower priority thread, it may not be able to quickly find weak reference objects
. 4. Virtual reference:

  As the name implies, it is a form of fictitiousness. If an object only holds virtual references, then it is equivalent to no references and may be recycled by the garbage collector at any time. 

Guess you like

Origin www.cnblogs.com/zeussbook/p/12716173.html