WeakReference and SoftReference, weakreference

Source: Internet
Author: User

WeakReference and SoftReference, weakreference

SoftReference (soft reference) and WeakReference (weak reference) are two classes used for java objects in heap. These two classes can be used for simple interaction with gc.

 

WeakReference is a weak reference, in which the stored object instance can be recycled by GC. This class is usually used to save the object reference somewhere without interfering with GC collection of the object. It is usually used in programs such as Debug and memory monitoring tools. This type of program generally requires that the object be observed and does not affect the normal GC process of the object.

Recently, Weakrefrence is also found in the JDK Proxy Class implementation code. The Proxy will save the dynamically generated Class instance to a Map consisting of Weakrefrence as the Cache.

 

SoftReference is a strongly referenced object instance. Unless JVM is about to OutOfMemory, it will not be recycled by GC. This feature makes it especially suitable for designing object Cache. For Cache, it is best to keep the cached object in the memory. However, if the JVM memory is tight, in order to avoid system crash caused by OutOfMemoryError, the JVM is allowed to reclaim the Cache memory when necessary, the data will be re-loaded to the Cache when appropriate. In this way, the system can be designed to be more flexible.

Strong reference
Object o=new Object();    Object o1=o;

In the above Code, the first sentence is to create an Object in the heap to reference this Object through o, and the second sentence is to create a reference to the Object in the heap through o from o1 to new Object, both references are strongly referenced. gc does not collect any reference to an object in heap. use the following code:

o=null;    o1=null;

If the values of o and o1 are explicitly set to null or out of the range, gc considers that the object does not have a reference, and then it can be collected. Collection is not equal to being collected in a short time. The collection time depends on the gc algorithm, which brings a lot of uncertainty. For example, if you want to specify an object and want to collect it during the next gc run, you can't do it. With the other two references, you can do it. The other two references can be used for simple interaction without interfering with gc collection.

In heap, objects can be strong and objects, soft and objects, weak and objects, virtual and accessible objects, and non-reachable objects. The order of application strength isStrong, soft, weak, and virtual. The most powerful reference of an object is the sum of objects. As follows:

 

WeakReference
import java.lang.ref.WeakReference;     public class WeakReferenceTest {         /**       * @param args       */      public static void main(String[] args) {           A a = new A();           a.str = "Hello, reference";           WeakReference<A> weak = new WeakReference<A>(a);           a = null;           int i = 0;           while (weak.get() != null) {               System.out.println(String.format("Get str from object of WeakReference: %s, count: %d", weak.get().str, ++i));               if (i % 10 == 0) {                   System.gc();                   System.out.println("System.gc() was invoked!");               }               try {                   Thread.sleep(500);               } catch (InterruptedException e) {                 }           }           System.out.println("object a was cleared by JVM!");       }     }

Program running result:

Get str from object of WeakReference: Hello, reference, count: 1  Get str from object of WeakReference: Hello, reference, count: 2  Get str from object of WeakReference: Hello, reference, count: 3  Get str from object of WeakReference: Hello, reference, count: 4  Get str from object of WeakReference: Hello, reference, count: 5  Get str from object of WeakReference: Hello, reference, count: 6  Get str from object of WeakReference: Hello, reference, count: 7  Get str from object of WeakReference: Hello, reference, count: 8  Get str from object of WeakReference: Hello, reference, count: 9  Get str from object of WeakReference: Hello, reference, count: 10  System.gc() was invoked!   object a was cleared by JVM!
SoftReference
import java.lang.ref.SoftReference;     public class SoftReferenceTest {         /**       * @param args       */      public static void main(String[] args) {           A a = new A();           a.str = "Hello, reference";           SoftReference<A> sr = new SoftReference<A>(a);           a = null;           int i = 0;           while (sr.get() != null) {               System.out.println(String.format("Get str from object of SoftReference: %s, count: %d", sr.get().str, ++i));               if (i % 10 == 0) {                   System.gc();                   System.out.println("System.gc() was invoked!");               }               try {                   Thread.sleep(500);               } catch (InterruptedException e) {                 }           }           System.out.println("object a was cleared by JVM!");       }     }
Summary

SoftReference is more powerful than WeakReference. When the JVM memory is not tight, Soft can retain reference to this object even if the referenced object is left empty, at this time, the JVM memory pool actually retains the original object. Only when the memory is tight will the JVM clear the Soft reference object and reload the referenced object in the future.
WeakReference automatically clears the referenced objects when the memory pool is cleared.

I am the dividing line of tiantiao

 

 

Reference: http://wiseideal.iteye.com/blog/1469295


What is the difference between weakReference and softReference?

Weak reference objects, which do not prohibit them from indicating that objects can be terminated, terminated, and recycled. Weak references are most commonly used for standardized ing. Assume that the Garbage Collector determines that an object is weak and reachable at a certain time point. At this time, it will automatically clear all weak references to this object, and through the strong reference chain and soft reference, it can be used to obtain all weak references from any other weak reachable objects. At the same time, it declares that all the previous weak reachable objects can be terminated. At the same time or later, it adds weak references that have been registered with the reference queue to the queue. **************************************** **************************************** ***********
SoftReference:
Soft reference object. when responding to memory needs, the garbage collector determines whether to clear this object. Soft reference objects are most commonly used for memory-sensitive caching. It is assumed that the Garbage Collector determines that an object is soft reachable at a certain time point. In this case, it can automatically clear all soft references for the object, and use the strong reference chain to get all soft references for any other soft reachable object. At the same time or later, it adds soft references that have been registered with the reference queue to the queue. All soft references of soft reachable objects must be cleared before the VM throws an OutOfMemoryError. Otherwise, the time when soft references are cleared or the order in which a group of such references of different objects are cleared is not subject to any constraints. However, virtual machine implementations do not encourage the removal of recently accessed or used soft references. Direct instances of this type can be used to implement simple caching. This type or its derived subclass can also be used in larger data structures to implement more complex caching. As long as the soft reference indicates that the object is strongly reachable, that is, the actually used object will not clear the soft reference. For example, by keeping a strong indicator object for recently used items and deciding whether to discard the remaining items by the garbage collector, a complicated cache can prevent the recent items from being discarded.
**************************************** ************
WeakReference is generally used to prevent memory leakage. Ensure that the memory is recycled by the VM.

WeakReference

A SoftReference shoshould be cleared and enqueued as late as possible, that is, in case the VM is in danger of running out of memory.

A soft reference should be cleaned up and written as late as possible. Therefore, in this case, the Virtual Machine (VM) has the risk of memory overflow (danger ).

My personal understanding: the problem lies in "as late as possible"-the risk of memory overflow (danger) is certainly raised when garbage is cleared too late ).
------------------------------------
All objects formerly being referenced by ref become eligible for finalization.
All objects referenced by ref will meet the condition of finalization.
Ref: Address reference. java refers to the object created by new.
Unless JNI is used, the memory occupied will not be in the ref range (Thinking in Java 4th, 120 pages)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.