Java softreference WeakReference

Source: Internet
Author: User

The Java 2 platform introduces the JAVA.LANG.REF package, which includes classes that allow you to reference objects without leaving them in memory. These classes also provide limited interaction with the garbage collector (garbage collector).

1. The first "from Strong to Weak" (only the relationship with the garbage collector) clarifies several basic concepts:
Strong references is the kind of reference you usually build, and this reference is strong. This is not automatically reclaimed by the garbage collector. For example:
StringBuffer buffer = new StringBuffer ();
Where this buffer is a strong reference, it is called "strong" depending on how it handles the relationship with garbage collector: it is not recycled in any way. It's strong enough. Strong references have a problem at some point, and a hash table example below is a good explanation. And there is a problem in the buffer, especially in the large structure of the film. We create an area in memory to place the picture buffer, so we want to have a pointer pointing to that area. Using a strong reference at this point forces the picture to remain in memory, which you need to remove manually when you feel you don't need it, or a memory leak.

The

      weakreference is similar to something that is optional. In the process of scanning the area of memory that the garbage collector thread governs, once an object with only a weak reference is found, it will reclaim its memory regardless of whether the current memory space is sufficient or not, and it is plainly a less strong. The garbage collector is required to keep an object in memory. However, because the garbage collector is a low-priority thread, it is not necessarily quick to discover objects that have only weak references. Often said unreachable and weak reference refers to a meaning. This may still be unclear, so I'll give you an example:
       you have a class called a widget, but for some reason it can't add a feature through inheritance. What do we do when we want to get some information out of this object? Let's say we need to monitor the serial number of each widget, but this widget doesn't have this attribute, and it's not inherited ... This time we thought of using HashMaps:serialNumberMap.put (widgets, Widgetserialnumber);
        It's not going to stop-it looks OK on the surface, but it's the widget that strong reference the problem. When we set the serialnumber of a widget to be unnecessary, we remove the mapping from the mapping table, otherwise we have a memory leak or an error (removing a valid serialnumber). This question sounds familiar, yes, it's a common problem in languages that don't have a garbage management mechanism, and we don't have to worry about it in Java. Because we have weakreference. We use the built-in Weakhashmap class, which is almost the same as the hash table HashMap, but the weakreference is used where key key is, and if a Weakhashmap key becomes garbage, then its corresponding entry is automatically removed. This solves the above problem ~

SoftReference is also similar to something that is dispensable. If the memory space is sufficient, the garbage collector does not reclaim it, and if the memory space is insufficient, the memory of those objects is reclaimed. The object can be used by the program as long as it is not reclaimed by the garbage collector. Soft references can be used to implement memory-sensitive caches.

The difference between a weak reference and a soft reference is that an object with WeakReference has a more ephemeral life cycle. Or softreference is not sensitive to recovering the object it refers to, than WeakReference. A WeakReference object is cleaned up in the next round of garbage collection, while the SoftReference object is saved for a period of time. SoftReferences does not take the initiative to ask for anything different from WeakReference, but in fact softreference objects are generally not removed when memory is plentiful, which means that they are a good choice for creating buffers. It has the benefits of strongreference and WeakReference, both in memory, but also in memory is to deal with, all this is automatic!

Phantomreference is a "virtual reference", as the name implies, is a dummy, unlike several other references, the virtual reference does not determine the object's life cycle. If an object holds only a virtual reference, it can be garbage collected at any time, just as there are no references, that is, its Get method will return null at any moment. Virtual references are primarily used to track the activities of objects that are garbage collected. It must be used in conjunction with the reference queue (Referencequeue), which is the largest difference from weak and soft references.

WeakReference the object before the garbage collection activity, in theory this object can also use the Finalize () method to regenerate it, but WeakReference is still dead. The Phantomreferences object is queued only when the object is purged from memory. That is, when the garbage collector prepares to reclaim an object, if it finds that it has a virtual reference, it will add the virtual reference to the reference queue associated with it before reclaiming the object's memory. The program can see if the referenced object is going to be garbage collected by judging whether the reference queue has been added to the virtual reference. If the program finds that a virtual reference has been added to the reference queue, it can take the necessary action before the memory of the referenced object is recycled. It restricts the use of the Finalize () method, which is more secure and more efficient.

2. Let's see what kind of package is available to us.
WeakReference class
WeakReference weakref = new WeakReference (ref);
This weakref is a weak reference that ref points to the object. You can use the Get method to reference the object that the weak reference points to. Put the object's weak reference into the Hashtable or cache, and the object can be reclaimed by the garbage collector when no strong reference points to them. In fact, there is a weakhashmap that specializes in doing this. Once weakreference returns null using the Get method, the object it points to has become garbage, and the Weakref object is useless. This will require some cleanup work. The Referencequeue class is doing this, and if you pass a WeakReference constructor to the Referencequeue class, the referenced object is automatically inserted into the reference queue when the referenced object becomes garbage. You can process this queue within a certain time interval.

SoftReference class
Can be used to implement smart caching (Java.lang.ref.SoftReference is a relatively new class, used to implement smart caches.)

Suppose you have an object reference that points to a large array:

Object obj = new char[1000000];
And if possible, you're going to keep the array, but if the memory is extremely scarce, you're happy to release the array. You can use a
Soft reference:
SoftReference ref = new SoftReference (obj);
obj is a reference to this soft reference. In the future you will detect this reference in the following way:
if (ref.get () = = null)//(Referent has been cleared)
else//(referent have not been cleared)
If the reference has been cleared, the garbage collector reclaims the space it uses and the object you cached has disappeared. Note that if the indicator has a different reference to it, the garbage collector will not clear it. This scheme can be used to implement a variety of different types of caches, which are characterized by the possibility that objects will be preserved as long as possible, but if the memory-intensive objects are erased.

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.