Home > Java > javaTutorial > Learning and understanding of Java weak references

Learning and understanding of Java weak references

WBOY
Release: 2023-04-25 18:25:09
forward
963 people have browsed it

What——What is a weak reference?

The weak reference in Java specifically refers to the java.lang.ref.WeakReference class. Let’s first take a look at the official document’s description of it:

The existence of a weak reference object will not prevent the object it points to from being recycled by the garbage collector. The most common use of weak references is to implement canonicalizing mappings (such as hash tables).

Assume that the garbage collector determines at a certain point in time that an object is weakly reachable (that is, all current points pointing to it are weak references), then the garbage collector will Clear all weak references to the object, and then mark the weakly reachable object as finalizable so that it will be recycled later. At the same time or later, the garbage collector will put the weak references that have just been cleared into the reference queue (Reference Queue) specified when creating the weak reference object.

Actually, there are four types of references in Java, which from strong to weak are: strong references, soft references, weak references, and virtual references. Below we briefly introduce the other three types of references except weak references:

  • Strong Reference: Usually when we create a new object through new, the reference returned is a strong reference. Reference, if an object is reachable through a series of strong references, it is strongly reachable, then it will not be recycled

  • Soft Reference: Soft Reference The difference between a reference and a weak reference is that if an object is reachable by a weak reference, it will be recycled regardless of whether the current memory is sufficient, while an object that is reachable by a soft reference will be recycled when the memory is insufficient, so a soft reference is better than a weak reference. References are "stronger"

  • Phantom Reference: Phantom Reference is the weakest reference in Java, so how weak is it? It is so fragile that we cannot even get the referenced object through a virtual reference. The only purpose of a virtual reference is that when the object it points to is recycled, the virtual reference itself will be added to the reference queue to record it. The pointed object has been recycled.

Why——Why use weak references?

Consider the following scenario: There is now a Product class representing a product. This class is designed to be non-extensible, and at this time we want to add a number to each product. One solution is to use HashMap. So the question arises. If we no longer need a Product object to exist in memory (for example, this product has been sold), assuming that the reference pointing to it is productA, we will assign the value of productA to null at this time. However, at this time The Product object that productA pointed to in the past will not be recycled because it is obviously still referenced by the HashMap.

So in this case, if we want to truly recycle a Product object, it is not enough to just assign its strong reference to null, but also to remove the corresponding entry from the HashMap. Obviously we don't want to complete the work of "removing no longer needed entries from HashMap" ourselves. We want to tell the garbage collector that when only the keys in the HashMap refer to the Product object, the corresponding Product object can be recycled. Obviously, according to the previous definition of weak reference, using weak references can help us achieve this goal. We only need to use a weak reference object pointing to the Product object as the key in the HashMap.

How——How to use weak references?

Take the scenario introduced above as an example. We use a weak reference object pointing to the Product object as the key of HashMap. We only need to define this weak reference object like this:

Product productA = new Product(...);
WeakReference weakProductA = new WeakReference<>(productA);

Now, if the object weakProductA is referenced It points to the Product object productA. So how do we get the Product object productA it points to through weakProduct? It's very simple. You only need the following code:

Product product = weakProductA.get();

In fact, for this case, the Java class The library provides us with the WeakHashMap class. When using this class, its key is naturally a weak reference object, and we do not need to manually wrap the original object. In this way, when productA becomes null (indicating that the Product it refers to no longer needs to exist in memory), then the weak reference object weakProductA points to the Product object, so obviously the corresponding Product object is weak at this time. Reachable, so the weak reference pointing to it will be cleared, the Product object will be recycled immediately, and the weak reference object pointing to it will enter the reference queue.

Reference Queue

Let’s briefly introduce the concept of reference queue. In fact, the WeakReference class has two constructors:

//创建一个指向给定对象的弱引用
WeakReference(T referent) 
//创建一个指向给定对象并且登记到给定引用队列的弱引用
WeakReference(T referent, ReferenceQueue<? super T> q)
Copy after login

We can see that the second constructor provides a parameter of type ReferenceQueue. By providing this parameter, we register the created weak reference object. to a reference queue, so that when it is cleared by the garbage collector, it will be sent to the reference queue, and we can uniformly manage these cleared weak reference objects.

The above is the detailed content of Learning and understanding of Java weak references. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template