search
HomeBackend DevelopmentXML/RSS TutorialStrong, soft, weak and virtual references of Java objects

In versions prior to JDK1.2, when an object is not referenced by any variable, the program can no longer use this object. That is, a program can only use an object if it is reachable. This is just like in daily life, after buying an item from a store, if it is useful, you keep it, otherwise you throw it into the trash can and be collected by the cleaners. Generally speaking, if an item has been thrown into the trash can, it is impossible to pick it up and use it again.

But sometimes the situation is not that simple. You may encounter items that are tasteless and tasteless, and it is a pity to throw them away. This kind of item is no longer useful now. Keeping it will take up space, but it is not cost-effective to throw it away immediately because it may be used in the future. For such dispensable items, a compromise approach is: if there is enough space in the home, keep it at home first. If there is not enough space in the home, even if all the garbage is removed from the home, it still cannot accommodate the indispensable items. If you don’t have enough daily necessities, then throw away these dispensable items.

Starting from JDK version 1.2, object references are divided into four levels, allowing the program to more flexibly control the life cycle of the object. These four levels, from high to low, are: strong reference, soft reference, weak reference and virtual reference.


1. Strong quotation

The quotations introduced earlier in this chapter are actually strong quotations, which are the most commonly used quotations. If an object has a strong reference, it is similar to an essential daily necessities, and the garbage collector will never reclaim it. When there is insufficient memory space, the Java virtual machine would rather throw an OutOfMemoryError error and cause the program to terminate abnormally, rather than arbitrarily recycling objects with strong references to solve the problem of insufficient memory.

2. Soft Reference



If an object only has soft references, it is similar to disposable daily necessities. If there is enough memory space, the garbage collector will not reclaim it. If there is insufficient memory space, the memory of these objects will be reclaimed. As long as the garbage collector does not collect it, the object can be used by the program. Soft references can be used to implement memory-sensitive caching.

Soft references can be used in conjunction with a reference queue (ReferenceQueue). If the object referenced by the soft reference is garbage collected, the Java virtual machine will add the soft reference to the reference queue associated with it.



3. Weak Reference

If an object only has a weak reference, it is similar to a disposable daily necessities. The difference between weak references and soft references is that objects with only weak references have a shorter life cycle. In the process of the garbage collector thread scanning the memory area under its jurisdiction, once an object with only weak references is found, its memory will be reclaimed regardless of whether the current memory space is sufficient. However, because the garbage collector is a very low priority thread, it may not necessarily find objects with only weak references quickly.

Weak references can be used in conjunction with a reference queue (ReferenceQueue). If the object referenced by the weak reference is garbage collected, the Java virtual machine will add the weak reference to the reference queue associated with it.

4. Phantom Reference (Phantom Reference)

As the name suggests, "Phantom Reference" is in name only. Unlike other references, a phantom reference does not determine the life cycle of the object. If an object holds only phantom references, it is as if it had no references and may be garbage collected at any time.
Virtual references are mainly used to track the activities of objects being garbage collected. One difference between virtual references, soft references and weak references is that virtual references must be used in conjunction with a reference queue (ReferenceQueue). When the garbage collector is preparing to recycle an object, if it finds that it still has a virtual reference, it will add the virtual reference to the reference queue associated with it before recycling the object's memory. The program can determine whether the referenced object will be garbage collected by determining whether a virtual reference has been added to the reference queue. If the program finds that a virtual reference has been added to the reference queue, it can take necessary actions before the memory of the referenced object is recycled.

In this book, "quote" can be used as either a verb or a noun. Readers should distinguish the meaning of "quote" according to the context.

Three classes are provided in the java.lang.ref package: SoftReference class, WeakReference class and PhantomReference class, which represent soft references, weak references and phantom references respectively. The ReferenceQueue class represents a reference queue, which can be used in conjunction with these three reference classes to track the activities of the Java virtual machine in recycling the referenced objects. The following program creates a String object, ReferenceQueue object and WeakReference object:

//Create a strong reference
String str = new String("hello");

//Create a reference queue, is a generic mark, indicating that the reference to the String object is stored in the queue
ReferenceQueue rq = new ReferenceQueue();

//Create a weak reference, which references "hello" object, and is associated with the rq reference queue
// is a generic mark, indicating that WeakReference will weakly reference the String object
WeakReference wf = new WeakReference(str, rq);

The above is the content of strong, soft, weak and virtual references of Java objects. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement
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
RSS in XML: Unveiling the Core of Content SyndicationRSS in XML: Unveiling the Core of Content SyndicationApr 22, 2025 am 12:08 AM

The implementation of RSS in XML is to organize content through a structured XML format. 1) RSS uses XML as the data exchange format, including elements such as channel information and project list. 2) When generating RSS files, content must be organized according to specifications and published to the server for subscription. 3) RSS files can be subscribed through a reader or plug-in to automatically update the content.

Beyond the Basics: Advanced RSS Document FeaturesBeyond the Basics: Advanced RSS Document FeaturesApr 21, 2025 am 12:03 AM

Advanced features of RSS include content namespaces, extension modules, and conditional subscriptions. 1) Content namespace extends RSS functionality, 2) Extended modules such as DublinCore or iTunes to add metadata, 3) Conditional subscription filters entries based on specific conditions. These functions are implemented by adding XML elements and attributes to improve information acquisition efficiency.

The XML Backbone: How RSS Feeds are StructuredThe XML Backbone: How RSS Feeds are StructuredApr 20, 2025 am 12:02 AM

RSSfeedsuseXMLtostructurecontentupdates.1)XMLprovidesahierarchicalstructurefordata.2)Theelementdefinesthefeed'sidentityandcontainselements.3)elementsrepresentindividualcontentpieces.4)RSSisextensible,allowingcustomelements.5)Bestpracticesincludeusing

RSS & XML: Understanding the Dynamic Duo of Web ContentRSS & XML: Understanding the Dynamic Duo of Web ContentApr 19, 2025 am 12:03 AM

RSS and XML are tools for web content management. RSS is used to publish and subscribe to content, and XML is used to store and transfer data. They work with content publishing, subscriptions, and update push. Examples of usage include RSS publishing blog posts and XML storing book information.

RSS Documents: The Foundation of Web SyndicationRSS Documents: The Foundation of Web SyndicationApr 18, 2025 am 12:04 AM

RSS documents are XML-based structured files used to publish and subscribe to frequently updated content. Its main functions include: 1) automated content updates, 2) content aggregation, and 3) improving browsing efficiency. Through RSSfeed, users can subscribe and get the latest information from different sources in a timely manner.

Decoding RSS: The XML Structure of Content FeedsDecoding RSS: The XML Structure of Content FeedsApr 17, 2025 am 12:09 AM

The XML structure of RSS includes: 1. XML declaration and RSS version, 2. Channel (Channel), 3. Item. These parts form the basis of RSS files, allowing users to obtain and process content information by parsing XML data.

How to Parse and Utilize XML-Based RSS FeedsHow to Parse and Utilize XML-Based RSS FeedsApr 16, 2025 am 12:05 AM

RSSfeedsuseXMLtosyndicatecontent;parsingtheminvolvesloadingXML,navigatingitsstructure,andextractingdata.Applicationsincludebuildingnewsaggregatorsandtrackingpodcastepisodes.

RSS Documents: How They Deliver Your Favorite ContentRSS Documents: How They Deliver Your Favorite ContentApr 15, 2025 am 12:01 AM

RSS documents work by publishing content updates through XML files, and users subscribe and receive notifications through RSS readers. 1. Content publisher creates and updates RSS documents. 2. The RSS reader regularly accesses and parses XML files. 3. Users browse and read updated content. Example of usage: Subscribe to TechCrunch's RSS feed, just copy the link to the RSS reader.

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 Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor