search
HomeJavajavaTutorialLearning and understanding of Java weak references

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)

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!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

Is Java Truly Platform Independent? How 'Write Once, Run Anywhere' WorksIs Java Truly Platform Independent? How 'Write Once, Run Anywhere' WorksMay 13, 2025 am 12:03 AM

JavaisnotentirelyplatformindependentduetoJVMvariationsandnativecodeintegration,butitlargelyupholdsitsWORApromise.1)JavacompilestobytecoderunbytheJVM,allowingcross-platformexecution.2)However,eachplatformrequiresaspecificJVM,anddifferencesinJVMimpleme

Demystifying the JVM: Your Key to Understanding Java ExecutionDemystifying the JVM: Your Key to Understanding Java ExecutionMay 13, 2025 am 12:02 AM

TheJavaVirtualMachine(JVM)isanabstractcomputingmachinecrucialforJavaexecutionasitrunsJavabytecode,enablingthe"writeonce,runanywhere"capability.TheJVM'skeycomponentsinclude:1)ClassLoader,whichloads,links,andinitializesclasses;2)RuntimeDataAr

Is java still a good language based on new features?Is java still a good language based on new features?May 12, 2025 am 12:12 AM

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

What Makes Java Great? Key Features and BenefitsWhat Makes Java Great? Key Features and BenefitsMay 12, 2025 am 12:11 AM

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

Top 5 Java Features: Examples and ExplanationsTop 5 Java Features: Examples and ExplanationsMay 12, 2025 am 12:09 AM

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!