Java Magic Hall: Four types of reference, Referencequeue and Weakhashmap

Source: Internet
Author: User

First, preface

JDK1.2 previously provided only one reference type--strong reference to object obj = New object (); . and JDK1.2 after our additional three options are soft-reference Java.lang. Ref. SoftReference , weak reference Java.lang. Ref. WeakReference and Virtual reference Java.lang. Ref. Phantomreference . The following will record the reference queue Java.lang for them and the associated connection . Ref. Referencequeue and Java.util.WeakHashMap 's study notes.

Two or four types of references

1. Strong references (strong Reference)

The most commonly used reference type, such as object obj = new Object (); The GC must not be recycled as long as the strong reference exists.

2. Soft reference (Soft Reference)

Used to describe a swimming but not necessary object, when the heap will occur when the Oom (out of memory) will be reclaimed by the soft reference point to the space, if the recovery is still insufficient space to throw oom.

Typically used to implement memory-sensitive caches.

Example: two sets of data manipulation scenarios for student information query operations

First, the information will be stored in memory, the subsequent query directly read the memory information; (Advantages: fast reading speed; disadvantage: Memory space has been accounted for, if the resource access is not high, then wasted memory space)

Each query is read from the database and then populated to the to return. (Advantage: The memory space will be collected by GC and will not be occupied; disadvantage: Existing to still exists before GC occurs, but still executes a database query, waste IO)

Resolved with soft references:

Referencequeue q =Newreferencequeue ();//get data and cacheObject obj =NewObject (); SoftReference SR=Newsoftreference (obj, q);//next time you useObject obj = (object) Sr.Get();if(obj = =NULL){  //when soft references are reclaimed, they are not retrieved againobj =NewObject ();}//clean up the soft reference objects that are left after being retractedSoftReferenceref=NULL; while((ref= Q.poll ())! =NULL){  //Cleanup Work}

3. Weak references (Weak Reference)

When a GC occurs, it must reclaim the memory space that the weak reference points to.

4. Virtual references (Phantom Reference)

Also known as a phantom reference or phantom Reference, a virtual reference does not affect the life cycle of an object, nor can it obtain an instance of an object through a virtual reference, only to receive a system notification when a GC occurs.

So now the question is, if there is more than one reference type for an object, how do you judge the accessibility of it? In fact, the rules are as follows:

1. The accessibility of a single reference chain is determined by the weakest reference type;
2. The accessibility of multiple reference chains is determined by one of the strongest reference types;

We assume that the reference to ① and ③ in Figure 2 is a strong reference, ⑤ is a soft reference, ⑦ is a weak reference, and for object 5 according to these two principles, the path ①-⑤ takes the weakest reference ⑤, so the path reference to object 5 is a soft reference. Similarly, ③-⑦ is a weak reference. The strongest reference is taken between the two paths, and object 5 is a soft object (which is recycled when oom is about to occur).

Soft references, weak references, and virtual references are abstract class Java.lang. Ref. Reference , and most of the operations related to the reference queue and GC are implemented in the abstract class Reference.

Third, reference queue (Java.lang.ref.ReferenceQueue)

Reference queues are used in conjunction with Reference subclasses, and when the reference object points to a memory space that is reclaimed by GC, the Reference object is appended to the end of the reference queue (source boolean enqueue (reference<? extends t> R) {/ * called only by Reference class * /description is only for Reference instance invocation and can only be called once). The reference queue has the following instance method:

reference<, extends t> referencequeue#poll () , an element that is out of the queue and returns null if the queue is empty.

reference<, extends t> referencequeue#remove () , out of the queue an element, if not, block until there are elements to be out of the team.

Reference< extends t> referencequeue#remove (long timeout) , out of the queue an element, If not, block until there are elements that can be out of the queue or exceed the number of milliseconds specified by timeout (because wait is implemented by using wait (long timeout), so time is not guaranteed).

Iv. java.lang.ref.Reference

Reference internally constructs a Reference type of one-way linked list through a field of {Reference} next . In addition, it also contains a referencequeue< the Super t> queue field holds the reference queue for the reference object, Use Referencequeue.null if not specified in the reference subclass constructor, which means that each soft, weak, and virtual reference object must be associated with a reference queue.

Reference also contains a static field {Reference} pending (default = NULL), which is used to hold a single-link list of reference objects that have been reclaimed by GC in memory space. Reference starts with a static code block to check that the Pending field is null by initiating the highest-priority daemon thread. If not NULL, the reference object is appended to the reference queue associated with the reference object along the unidirectional list (unless the reference queue is Referencequeue.null). The source code of the daemon thread is as follows:

     Public voidrun () { for (;;)        {Reference R; Synchronized (Lock) {
Check if pending is nullif(Pending! =NULL) {R=pending; Reference RN=R.next; Pending= (Rn = = r)?NULL: RN; R.next=R; } Else { Try {
When pending is null, the current thread enters the wait set, waiting for the GC to execute NotifyallLock. Wait (); } Catch(Interruptedexception x) {}Continue; } } //Fast path for Cleaners if(r instanceof Cleaner) {((Cleaner) R). Clean (); Continue; }//Append to the corresponding reference queue Referencequeue Q=R.queue; if(Q! =referencequeue.null) Q.enqueue (R); } }

Note: Because of the creation and initiation of threads through static blocks of code, all child class instances of reference are appended to the reference queue by the same thread for the operation of the referencing object.

Wu, Java.util.WeakHashMap

Because the key object of the Weakhashmap is a weak reference, when the GC occurs, the memory space that the key object points to will be recycled, and when it is recycled, the instance method of the private Expungestaleentries method is called directly or indirectly, such as size, clear, or put. Those key objects that have been reclaimed (Entry) will be removed from the set of key-value pairs.

The following code will occur in Oom

 Public Static voidMain (string[] args) throws Exception {List<WeakHashMap<byte[][],byte[][]>> maps =Newarraylist<weakhashmap<byte[][],byte[][]>>();  for(inti =0; I < +; i++) {Weakhashmap<byte[][],byte[][]> d =Newweakhashmap<byte[][],byte[][]>(); D.put (New byte[ +][ +],New byte[ +][ +]);            Maps.add (d);            System.GC ();        System.err.println (i); }    }

The following code does not occur because the entry of the collection is removed so Oom

 Public Static voidMain (string[] args) throws Exception {List<WeakHashMap<byte[][],byte[][]>> maps =Newarraylist<weakhashmap<byte[][],byte[][]>>();  for(inti =0; I < +; i++) {Weakhashmap<byte[][],byte[][]> d =Newweakhashmap<byte[][],byte[][]>(); D.put (New byte[ +][ +],New byte[ +][ +]);              Maps.add (d);              System.GC ();                System.err.println (i);  for(intj =0; J < I; J + +) {
Trigger Remove Entry Operation System.err.println (J+"size"+ Maps.Get(j). Size ()); } } }

Vi. Summary

Respect the original, reprint please indicate from: http://www.cnblogs.com/fsjohnhuang/p/4268411.html ^_^ Fat Boy John

Vii. Reference

"The Myth of Weakhashmap" http://www.javaeye.com/topic/587995

http://hongjiang.info/java-referencequeue/

Java Magic Hall: Four types of reference, Referencequeue and Weakhashmap

Related Article

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.