Understanding weak references in Java (Weak Reference)

Source: Internet
Author: User

This article attempts to explore the weak references in Java from the three perspectives of what, why, and how, and to understand the definition of weak references in Java, basic usage scenarios, and how to use them. Because of the limited personal level, there is inevitably inaccurate or unclear in the narrative, I hope you can point out, thank you all:

1. what--What is a weak reference?

Weak references in Java refer specifically to the Java.lang.ref.weakreference<t> class, so let's start by looking at what the official documentation says about it:

The presence of a weak reference object does not prevent the object it points to from being reclaimed by the garbage collector. The most common use of weak references is to implement canonical mappings (canonicalizing mappings, such as a hash table).

Assuming that the garbage collector determines at some point that an object is weakly accessible (weakly reachable)(that is, all that is currently pointing to it is a weak reference), the garbage collector clears all weak references to that object. The garbage collector then marks the weakly-accessible object as finalizable, so that they are then recycled. At the same time or later, the garbage collector puts the weak references that were just purged into the reference queue (Reference queue) that was enlisted when the weak reference object was created.

In fact, there are four types of references in Java, from strong to weak: Strong references, soft references, weak references, and virtual references. The following is a brief introduction to the other three references except weak references:

    • Strong references (strong Reference): Usually the reference returned when we create a new object through new is a strong reference, and if an object is reachable by a series of strong references, it is strong (strongly reachable), then it is not recycled
    • Soft references (Soft Reference): The difference between soft and weak references is that if an object is a weak reference, it will be reclaimed regardless of the current memory adequacy, and the soft reference can be reclaimed when the object is not fully memory, so soft references are "stronger" than weak references.
    • Virtual reference (Phantom Reference): A virtual reference is the weakest reference in Java, so how weak is it? It is so fragile that we cannot even get to the referenced object through a virtual reference, and the only thing that a virtual reference exists is that when the object it points to is reclaimed, the virtual reference itself is added to the reference queue as a record that the object it points to has been destroyed.

2. Why do why--use weak references?

Consider the following scenario: Now that there is a product class that represents one of the products, this class is designed to be non-extensible, and at this point we want to add a number to each product. One solution is to use Hashmap<product, integer>. So the question is, if we no longer need a product object in memory (for example, it has been sold), assuming that the reference to it is producta, we will assign a value of NULL to PRODUCTA, However, the product object that ProductA used to point to is not recycled because it is clearly referenced by HashMap. So in this case, we want to really recycle a product object, it is not enough to simply assign its strong reference to null, and to remove the corresponding entry from the HashMap. Obviously "remove items that are no longer needed from HashMap" We don't want to do it ourselves, we want to tell the garbage collector that the product object can be recycled only if the key in HashMap is referencing the Product object. Obviously, using weak references can help us achieve this, based on the definition of the previous weak reference. We just need to use a weak reference object that points to the product object as a key in the HashMap.

3. how--How do I use weak references?

With the example of the scenario described above, we use a weak reference object that points to the product object as a key to HashMap, and we simply define this weak reference object:

ProductA = new Product (...); weakreference<product> weakproducta = new weakreference<> (PRODUCTA);

Now, referencing the object Weakproducta points to the Product object producta. So how do we get the Product object producta it points to by weakproduct? Very simple, just need the following code:

Product Product = Weakproducta.get ();

In fact, for this case, the Java class Library provides us with the Weakhashmap class, and this class, whose key is naturally a weak reference object, does not require us to manually wrap the original object. This way, when producta becomes null (indicating that the product it refers to does not need to exist in memory), the object that points to the product is weakproducta by the weakly referenced objects, then obviously the corresponding product object is weakly accessible , so a weak reference to it is cleared, and the product object is recycled, and the weak reference object that points to it goes into the reference queue.

Let's take a brief introduction to the concept of the reference queue. In fact, the WeakReference class has two constructors:

WeakReference (t referent)//Create a weak reference to a given object WeakReference (t referent, referencequeue<? super t> Q)// Creates a weak reference that points to the given object and enlists to the given reference queue

We can see that the second constructor provides a parameter of type Referencequeue, by providing this parameter, we register the weak reference object created on a reference queue, so that when it is purged by the garbage collector, it is fed into the reference queue. We can manage these weakly referenced objects that are cleared.

4. References

(1) weakreference (Java Platform SE 7)-Oracle help Center

(2) Understanding weak references in Java

Classification:Summary of Java Core Technology points

Understanding weak references in Java (Weak Reference)

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.