Understanding of WeakReference and Weakhashmap in Java

Source: Internet
Author: User

There is a choice question in the October 11 written test of the New American and big, let the selection function return the result, the code is as follows:

1 Private StaticString Test () {2String A =NewString ("a");3Weakreference<string> B =NewWeakreference<string>(a);4weakhashmap<string, integer> weakmap =NewWeakhashmap<string, integer>();5Weakmap.put (B.get (), 1);6A =NULL;7 System.GC ();8String C = "";9         Try{Tenc = B.get (). Replace ("A", "B"); One             returnC; A}Catch(Exception e) { -c = "C"; -             returnC; the}finally{ -c + = "D"; -             returnC + "E"; -         } +}

The result of the operation is "CDE".

The key is to examine the understanding of weakreference and Weakhashmap.

Just a little bit. Java GC Content

In Java, when an object is created, it is placed in the heap. When the GC is running, if no references are found to the object,object it will be reclaimed to free up memory space. Or in other words, an object is recycled and must meet two conditions: 1) Without any references to it 2) the GC is run.

WeakReference

When an object is simply pointed to by the weak reference (weak reference), and no other strong reference (strong reference) points, the object is recycled if the GC is running. The syntax of weak reference is:

weakreference<t> weakref  new weakreference<t> ();

When you want to obtain an object of WeakReference, you first need to determine if it has been reclaimed by GC, and if it is retracted, the following return value is null:

Weakref.get ();

So in the above code, after A=null; System.GC (), after weakreference<string> B = new Weakreference<string> (a), A is empty and the system has been retracted, and B has no strong reference point, So B was also taken back by the system GC. So when the code runs to C = B.get (). Replace ("A", "B"), the exception is thrown because B.get () is null.

Weakhashmap

Weakhashmap is actually similar to HASHMAP usage, the only difference between them is that the key in HashMap is a strong reference to the actual object, so as long as the object is not destroyed, the corresponding key-value of that key is not recycled by the garbage collection mechanism. However, the actual object saved by Weakhashmap is a weak reference, which means that it is possible for the object to be reclaimed by the garbage collection mechanism if it is not referenced by a strong object. Key-value. Examples are as follows:

ImportJava.util.WeakHashMap;    Public classWeakhashmaptest { Public Static voidMain (string[] args) {Weakhashmap W=NewWeakhashmap (); //three keys in Key-value are anonymous objects, no strong references point to the actual objectW.put (NewString ("language"),NewString ("excellent")); W.put (NewString ("math"),NewString ("Pass")); W.put (NewString ("English"),NewString ("Medium")); //Add a strong reference to a stringW.put ("Java",NewString ("exceptionally good"));          System.out.println (w); //notifies the garbage collection mechanism to recycleSystem.GC ();          System.runfinalization (); //Output W againSYSTEM.OUT.PRINTLN ("Secondary output:" +W); }    }  

Output: {Java= is very good, maths = pass, English = medium, language = excellent}
Second output w:{java= very good}

So in the beginning of the code weakhashmap<string, integer> weakmap = new weakhashmap<string, integer> (); Weakmap does not have a strong reference guideline, so Weakmap is retrieved by the system GC after executing System.GC ().

Print out the variables in the code

1 Private StaticString Test () {2String A =NewString ("a");3         //System.out.println (a);4Weakreference<string> B =NewWeakreference<string>(a);5         //System.out.println (B.get ());6weakhashmap<string, integer> weakmap =NewWeakhashmap<string, integer>();7Weakmap.put (B.get (), 1);8A =NULL;9SYSTEM.OUT.PRINTLN ("GC Before B.get ():" +b.get ());TenSYSTEM.OUT.PRINTLN ("GC before Weakmap:" +weakmap); One System.GC (); ASystem.out.println ("post-GC" +b.get ()); -System.out.println ("post-GC" +weakmap); -String C = ""; the         Try{ -c = B.get (). Replace ("A", "B"); -System.out.println ("C:" +c); -             returnC; +}Catch(Exception e) { -c = "C"; +System.out.println ("Exception"); A             returnC; at}finally{ -c + = "D"; -             returnC + "E"; -         } -}

After running the result is:

GC Pre-b.get (): AGC before Weakmap:{a=1}gc after NULLGC {}EXCEPTIONCDE

Visible, changes in WeakReference and Weakhashmap before and after System.GC ().

The relationship between try,catch,finally in exception handling in Java

In Java exception handling,
Without throwing an exception, after the program executes the code block inside the try, the method does not end immediately, but continues to try to find the method has no finally block of code,
If there is no finally code block, the entire method returns the corresponding value after executing the try code block, ending the entire method;
If there is a finally code block, the program executes to the return statement in the try code block without immediately executing the return ( if the return is a statement or function, Eg:return b+=10; or return Functiona (); Execute the RETURN statement or function first , and then execute the code in the finally code block,
If there is no return in the finally code block or no code to terminate the program, the program will return a try code block after executing the finally code block code to execute the return statement to end the entire method;
If there is a return in the finally code block or contains code that terminates the program, the method will be ended after the finally execution and no longer jumps back to the try code block to execute return.
In the case of throwing an exception, the principle is the same as above, you put the above-mentioned try to catch to understand the OK.

Now analyze the above code:

B.get () and weakmap are null after System.GC ()

Throw exception in try, catch exception in Catch

Executes C = "C", executes to return C, but does not immediately return, executes finally

Execute c + = "D"; Return C + "E", there is a return statement in the finally code block will not return the catch to execute return.

So the end result is return "CDE"

Understanding of WeakReference and Weakhashmap in Java

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.