The understanding and use of Java WeakReference

Source: Internet
Author: User

Introduction: See a post, a foreign technical interviewer in the interview senior Java developer, asked a weak reference related issues. He did not expect anyone to fully explain what weak reference was, how to use it, just to expect someone to mention this concept and Java GC-related. Unfortunately, only two of the more than 20 interviewers with more than 5 years of experience in Java development know the existence of weak reference, and only one of them actually used him. Undoubtedly, in the eyes of interviewer, the understanding and application of weak reference in the interview gave this a interviewee quite a lot of extra points. So, my understanding and use of this technology in this blog, I hope readers and themselves through reading and writing this post, can be in the future work and interview to get extra points.

In Java, when an object o is created, it is placed in the heap. When the GC is running, if no references to O are found, O 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.

When it comes to writing code, we tend to make sure that the object is recycled at the next GC when it runs (you can use JAVA-VERBOSE:GC to observe the behavior of the GC) by referece all points to an object.

New Car (); c=null;

However, manually placing empty objects is cumbersome and inconsistent with the idea of automatic recycling for programmers. For a simple case, manual empty is not required by the programmer, because in Java, for a simple object, when the method that invokes it finishes executing, the reference to it will be popup from the stack, so that he can be recycled the next time the GC executes.

However, there are special exceptions. When using the cache, because the cache object is exactly what the program needs to run, as long as the program is running, the reference in the cache will not be given to the GC (or the reference in the cache has the same life cycle as the main program). With more and more reference in the cache, the object that the GC cannot reclaim is becoming more and more, and cannot be automatically recycled. When these objects need to be recycled, the task of reclaiming these objects is only given to the program writer. This, however, violates the nature of GC (automatic recycling of objects that can be recycled).

As a result, weak reference is introduced in Java. Relative to the strong reference in the preceding example:

As long as c also points to car object, car object will not be recycled

When an object is directed only by weak reference, and no other strong reference points, the object is recycled if the GC is running. The syntax of weak reference is:

weakreference<car> Weakcar = new weakreference<car> (Car);  

When you want to get the object referenced by weak reference, you first need to determine whether it has been recycled:

Weakcar. Get ();

If this method is empty, then the object pointed to by Weakcar has been recycled.

Let's look at an example:

Package weakreference;/** *@author Wison * *PublicClassCar {PrivateDouble Price;Private String colour;PublicCar(Double price, String colour) {This.price = Price;This.colour = colour;}PublicDoubleGetPrice() {return price;public void setPrice (double price) {this.price = Price;} public String getColour () {return colour;} public void setcolour (String colour) { This.colour = colour;} public String toString () {return colour + "car costs $" +price;}   
Package Weakreference;import Java.lang.Ref. WeakReference;/** * @author Wison * *PublicClasstestweakreference {PublicStaticvoidmain (string[] args) {Car car = new Car (22000, "silver"); weakreference<car> Weakcar = new weakreference<car> (Car); int i=0; while (true) {if (Weakcar. Get ()!=null) {i++; System. out.println ( "Object is alive for" +i+  "loops-" +weakcar); else{system. Out.println ( "Object has been collected."); break;}}}             

In the example above, after the program has been running for a period of time, the program prints out the "object has been collected." Description, weak reference the object that is pointing to is recycled.

It is worth noting that even if a car reference is directed to an object and car is a strong reference, the object weak reference Weakcar points to is still being recycled. This is because the Java compiler has not been used since it was found to have entered the while loop, so it was optimized (empty?). When the Testweakreference.java is modified to:

Package Weakreference;import Java.lang.Ref. WeakReference;/** * @author Wison * *PublicClasstestweakreference {PublicStaticvoidMainString[] args) {Car car =New Car (22000, "silver"); weakreference<car> Weakcar = new weakreference<car> (Car); int i=0; while (true) {system. Out.println ( "Here is the strong reference ' car '" +car);  Get ()!=null) {i++; System. out.println ( "Object is alive for" +i+  "loops-" +weakcar); else{system. Out.println ( "Object has been collected."); break;}}}             

The object pointed to by weak reference will not be recycled. Because there is also a strong reference car pointing to it.

* One feature of WeakReference is that it is not deterministic when it is recycled, as this is determined by the uncertainty of the GC operation. Therefore, objects that are typically referenced by weak reference are objects that are valuable to the cache and are easily rebuilt and consume memory.

Referencequeue

Weak reference itself is useless after the object that weak reference points to is recycled. Java provides a referencequeue to hold the reference that the object pointed to has been recycled. The usage is to pass a Referencequeue object as a parameter to the constructor when defining WeakReference.

Other types of references

-softreference

Soft reference and weak reference, but it takes one more condition to be recycled by GC: When the system is out of memory (how does GC determine that the system is running out of memory?) can I configure this threshold?), soft The object that reference points to will be recycled. Because of this feature, soft reference is more suitable for the objects of cache reference than weak reference. Because it can retain cached objects as much as possible, reducing the time and consumption needed to rebuild them.

-phantomreference

This has not been thought of the application scenario, let's not say. If someone uses it in practice, you are welcome to share it.

Weakhashmap

The understanding and use of Java WeakReference

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.