Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the concept and function of weak reference in Java

2025-04-06 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the relevant knowledge of "what is the concept and function of weak citation in Java". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Overview

This article will start with the definition of weak reference, and then analyze its principle step by step through the use of cases, so as to let readers have a deep understanding of what weak reference is, how to use weak reference, and what scenarios will use weak reference. what kind of problems can weak references solve, and what is its source code implementation, which will involve memory overflow and garbage collection principles?

Function:

The jdk official website explains:

Weak references are mainly used in mapping that does not prevent its key or value from being recycled. Post it directly in English, with limited translation (weak references are for implementing canonicalizing mappings that do not prevent their keys (or values) from being reclaimed)

Personal understanding:

Weak references appear for garbage collection services. It references an object, but does not prevent the object from being recycled. If a strong reference is used, the referenced object cannot be recycled as long as the reference exists. Weak references do not have this problem. When the garbage collector is running, if all references to an object are weak references, the object will be reclaimed

Case in-depth analysis

Ideally, we want to be able to recycle an object when gc occurs when we no longer use it. But sometimes, due to our carelessness, it can lead to memory overflow in bad cases. This case especially occurs when a map with a long life cycle stores a lot of objects with a short actual life cycle. Take a look at the following example

Output the result after running:

Before the occurrence of gc: 1 start to notify GC gc after the occurrence: 1

As you can see from the output, even if we tell jvm that we no longer use this object by setting key and value to null, the objects in map are still not reclaimed by GC, because key and value are pointed to by a strong reference map. According to reachability, the garbage collector cannot recycle key and value. Map is defined as a static variable of statis and is an object with a long life cycle. There is a local variable of key and value in the strongTest () method, and as the method is executed, the life cycle of this variable ends, but the rough programmer forgets remove, and the garbage collector cannot collect it at this time. If there are a large number of objects with a relatively short life cycle, it is possible to consume all the memory in JVM eventually.

But I have a curiosity here, if the object pointed to by key and value here is no longer needed after executing the strongTest () method, but I may not have a good judgment to actively call remove to remove it. Do you want the garbage collector to judge whether it can be recycled or not? The answer is actually yes, at this time is the weak quote on the stage, please see the following program

Run the above code to output the result

Before the occurrence of gc: 1 start to notify GC gc after the occurrence: 0

From the output result of 0, we can judge that it has been successfully garbage collected. What? In the whole process, we just changed HashMap to WeakHashMap, and key from String to WeakReference. In fact, it is because the string has only weak reference points, so it can be garbage collected. Isn't it very simple? if you stop studying weak citations at this point, it would be too violent.

WeakHashMap in-depth analysis

In the above program snippet, only key is set to weak reference new WeakReference (key), so normally only the memory corresponding to this key is reclaimed. Since remove is not called, the value and entry in it will not be recycled, so why is the final output size 0? Good question, let's take a closer look at the source code of WeakHashMap, and we found a magic method, expungeStaleEntries (). Parse the concept of the reference queue before looking at the source code: when the weak reference is recycled, the object will be put into the reference queue, which means that the objects obtained from the reference queue are all recycled objects. This is enough to satisfy our following source code analysis, and then we will do a detailed analysis.

From the above code snippet, it roughly means that the recycled object is extracted from the reference queue, and then looked up with the object in WeakHashMap. After finding it, the corresponding value is also set to null, and the corresponding entry is set to null to tell GC to recycle it. You can see from the source code that the method expungeStaleEntries () will be called when any method in WeakHashMap is executed.

At this point, you can fully understand why value can be recycled even if it is not set to weak references and calls to remove methods that are not explicit.

Reference queue

From the above source code, we probably know the use of reference queues, so why use reference queues? If there is no reference queue, the above example we need to traverse all the elements one by one to find, if the number is small, if the number is large, there will certainly be some performance problems. With the reference queue, it is easy to solve the above problem. From the WeakReference source code, we can see that there are two constructors. The second one is the one that needs to pass in the reference queue.

Reference queue hello word

Details to pay attention to in use: since weakly referenced objects may be recycled when GC occurs, we all need to determine whether it is null to avoid null pointer exceptions before using it.

Summary

Weak references appear for garbage collection.

When an object has only a weak reference to it, it can be recycled

Weak references are reclaimed when GC occurs, regardless of whether there is enough memory at the time

If you specify a reference queue when you create a weak reference, when the weak reference object is recycled, it will be put into the reference queue

For safe use, it is necessary to judge whether the object is empty each time to determine whether the object has been reclaimed so as to avoid null pointer exceptions.

This is the end of the content of "what is the concept and function of weak citation in Java". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 228

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report