SoFunction
Updated on 2025-04-13

Detailed explanation of strong references, soft references, weak references and virtual references in Java

Overview

In Java, memory management is a very important topic. Java's Garbage Collection (GC) automatically manages memory, but developers still need to understand how to control the life cycle of an object through reference types. Java provides four reference types: Strong Reference, Soft Reference, Weak Reference and Phantom Reference. Each reference type has different impact on garbage collection and is suitable for different scenarios.

Next we will dive into these four reference types and combine them with actual code examples to better understand their usage scenarios and how they work. At the same time, we will also introduce the role of the reference queue (ReferenceQueue) and how to use it to track the recycling status of the object.

1. Strong Reference

1.1 What is a strong citation?

Strong references are the most common reference type in Java. If an object has a strong reference, the garbage collector will not recycle the object, and will not recycle it even if there is insufficient memory. Strong references are the default reference type, and most of the references we use in daily development are strong references.

Object obj = new Object(); // obj is a strong quote

1.2 Features of Strong Quotation

  • Objects will not be recycled: As long as a strong reference exists, the object will not be recycled by the garbage collector.
  • Explicit release: Only when the strong reference is explicitly set tonull, or when the scope is exceeded, the object will be garbage collected.
obj = null; // The object can now be recycled

1.3 Use scenarios for strong reference

Strong references are suitable for objects that must exist for a long time. For example, objects, singleton objects, etc. in core business logic. Since strong references prevent garbage collection, you need to be careful to avoid memory leaks when using strong references.

1.4 Things to note when citing strongly

  • Memory leak: If a strong reference has always existed but the object is no longer used, it may cause memory leakage. For example, if objects in the cache are not cleaned up in time, it may cause excessive memory usage.
  • Explicit release: When objects are no longer needed, strong references should be explicitly set tonull, to help the garbage collector recycle memory in time.

2. Soft Reference

2.1 What is a soft reference?

Soft references are used to describe some useful but not necessary objects. The garbage collector recycles the object pointed to by the soft reference only when the memory is insufficient. Soft citations are weaker than strong citations, but stronger than weak citations.

SoftReference<Object> softRef = new SoftReference<>(new Object());

2.2 Features of soft citations

  • Recycle when memory is insufficient: When memory is sufficient, the objects pointed to by the soft reference will not be recycled; but when memory is insufficient, the garbage collector will recycle these objects.
  • Suitable for caching: Soft references are often used to implement memory-sensitive caches. For example, when caching resources such as images and files, soft references can be used.
Object obj = (); // Get the object pointed to by the soft reference, which may be null

2.3 Use scenarios for soft reference

Soft references are ideal for implementing caching. For example, in Android development, soft references can be used to cache image resources. When memory is sufficient, image resources will be retained in the cache; when memory is insufficient, the garbage collector will automatically recycle these resources to avoid memory overflow.

2.4 Notes on soft citations

  • Performance overhead: The implementation of soft references requires additional overhead, so it needs to be used with caution in performance-sensitive scenarios.
  • Unreliability: Since the object pointed to by the soft reference may be recycled, a null value check is required when obtaining the object.

3. Weak Reference

3.1 What is a weak reference?

Weak citations are weaker than soft citations. Objects pointed to by weak references will be recycled the next time the garbage collection, regardless of sufficient memory.

WeakReference<Object> weakRef = new WeakReference<>(new Object());

3.2 Characteristics of weak citations

  • Recycle now: Objects pointed to by weak references will be recycled the next time the garbage collection is collected, even if the memory is sufficient.
  • Suitable for temporary caching: Weak references are usually used to implement temporary caches or mapping tables, allowing objects to be recycled when there are no strong references.
Object obj = (); // Get the object pointed to by a weak reference, which may be null

3.3 Use scenarios for weak references

Weak references are ideal for implementing temporary caching. For example, in JavaWeakHashMapIn, the key object is saved through weak references. When the key object has no other strong reference, the garbage collector will automatically recycle it and fromWeakHashMapRemove the corresponding entry in .

3.4 Things to note when citing weakly

  • Short life cycle of the object: Since objects pointed to by weak references are recycled immediately, they are not suitable for objects that require long-term storage.
  • Null value check: When obtaining objects pointed to by weak references, null value checks must be performed.

4. Phantom Reference

4.1 What is a virtual reference?

Virtual reference is the weakest type of reference. The virtual reference cannot be passedget()The method gets the object, and it exists only to receive a system notification when the object is recycled.

ReferenceQueue<Object> queue = new ReferenceQueue<>();
PhantomReference<Object> phantomRef = new PhantomReference<>(new Object(), queue);

4.2 Features of virtual citations

  • Unable to get object:Virtual referenceget()Methods always returnnull
  • Recycling notice: Virtual reference is mainly used to track the state of garbage collected by objects. When the object is recycled, the virtual reference will be placed in the associatedReferenceQueuemiddle.
Object obj = (); // Always return null

4.3 Use scenarios for virtual reference

Virtual references are usually used to implement resource cleaning mechanisms. For example, in JavaDirectByteBufferIn, virtual reference is used to free direct memory when an object is recycled.

4.4 Things to note when citing virtual quotes

  • Unable to get object: Due to false referenceget()Methods always returnnull, therefore, the object cannot be accessed directly through virtual references.
  • Complex implementation: The implementation of virtual references is usually complex and requires combinationReferenceQueueuse.

5. ReferenceQueue

5.1 What is a reference queue?

Reference queues can be used with soft references, weak references, and virtual references. When the object pointed to by the reference is recycled, the reference itself is placed in the reference queue. Developers can check the queue to know that the object has been recycled.

ReferenceQueue&lt;Object&gt; queue = new ReferenceQueue&lt;&gt;();
WeakReference&lt;Object&gt; weakRef = new WeakReference&lt;&gt;(new Object(), queue);

// When the object is recycled, weakRef will be placed in the queue

5.2 Use scenarios for reference queues

Reference queues are usually used to implement tracing mechanisms for object recycling. For example, when implementing a custom cache, a reference queue can be used to clean up recycled objects.

5.3 Notes on referring to queues

  • Queue Check: Reference queues need to be checked regularly to process recycled objects

Reference queue (ReferenceQueue) is usually referenced with soft references (SoftReference), weak reference (WeakReference) and virtual references (PhantomReference) Use together. When the object pointed to by the reference is recycled by the garbage collector, the reference itself is placed in the reference queue. By regularly checking the reference queue, developers can know which objects have been recycled, thus performing some cleaning operations.

Use case: Object recycling tracking and resource cleaning

Suppose we have a resource management class that is responsible for managing some resources that need to be cleaned (such as file handles, network connections, etc.). We want to perform automatic cleaning operations when these resources are garbage collected. To achieve this we can use virtual references (PhantomReference) and reference queue (ReferenceQueue)。

Implementation steps

  • Create a resource class that represents the resources that need to be managed.
  • Use virtual references and reference queues to track the recycled state of resources.
  • Regularly check the reference queue and perform resource cleaning operations.

Code implementation

1. Resource category

First, we define a resource classResource, indicates the resources that need to be managed.

class Resource {
    private String name;

    public Resource(String name) {
         = name;
        ("Resource created: " + name);
    }

    public void close() {
        ("Resource closed: " + name);
    }
}

2. Resource cleaning category

Next, we define a resource cleaning classResourceCleaner, used to track the recovery status of resources and perform cleaning operations.

import ;
import ;

public class ResourceCleaner extends PhantomReference&lt;Resource&gt; {
    private String name;

    public ResourceCleaner(Resource resource, ReferenceQueue&lt;? super Resource&gt; queue) {
        super(resource, queue);
         = (); // Save the resource's identity    }

    public void clean() {
        // Perform resource cleaning operations        ("Cleaning up resource: " + name);
    }
}

3. Resource Management

Then, we define a resource management classResourceManager, responsible for managing resources and regularly checking reference queues.

import ;

public class ResourceManager {
    private ReferenceQueue&lt;Resource&gt; queue = new ReferenceQueue&lt;&gt;();

    public void registerResource(Resource resource) {
        // Create a virtual reference and associate a reference queue        ResourceCleaner cleaner = new ResourceCleaner(resource, queue);
        ("Resource registered: " + resource);
    }

    public void checkQueue() {
        // Check the reference queue and process the recycled resources        ResourceCleaner cleaner = (ResourceCleaner) ();
        while (cleaner != null) {
            (); // Perform a cleanup operation            cleaner = (ResourceCleaner) ();
        }
    }
}

4. Test code

Finally, we write test code to verify resource recycling and cleaning mechanisms.

public class ReferenceQueueExample {
    public static void main(String[] args) throws InterruptedException {
        ResourceManager manager = new ResourceManager();

        // Create a resource and register        Resource resource1 = new Resource("Resource-1");
        (resource1);

        // Simulation resources are no longer strongly cited        resource1 = null;

        // Trigger garbage collection        ();

        // Wait for a while to ensure that the garbage collection is completed        (1000);

        // Check the reference queue and perform a cleanup operation        ();
    }
}

Code running results

After running the above code, the output is as follows:

Resource created: Resource-1
Resource registered: Resource@1b6d3586
Cleaning up resource: Resource@1b6d3586

Results Analysis

  • Created a resource objectResource-1and register it withResourceManagermiddle.
  • Willresource1Set tonull, so that it will no longer be forced to quote.
  • Call()Trigger garbage collection.
  • The garbage collector has been recycledResource-1, and put its virtual reference into the reference queue.
  • Call()Check the reference queue and perform resource cleaning operations.

Key points analysis

  • The role of virtual citation

    • The virtual reference cannot be passedget()Methods obtain objects, so they will not affect the life cycle of objects.
    • The main function of virtual reference is to track the state of the object being recycled.
  • The role of a reference queue

    • When the object pointed to by the virtual reference is recycled, the virtual reference will be placed in the reference queue.
    • By checking the reference queue, you can know which objects have been recycled.
  • Resource cleaning mechanism

    • After the resource is recycled, cleanup operations are performed through the reference queue (such as closing the file handle, freeing memory, etc.).
    • This mechanism can avoid resource leakage.

Extension: Check the reference queue regularly

In practical applications, it may be necessary to check the reference queue regularly to ensure that the recycled resources are cleaned up in a timely manner. Regular inspections can be achieved by:

Use daemon threads to check regularly

public class ResourceManager {
    private ReferenceQueue&lt;Resource&gt; queue = new ReferenceQueue&lt;&gt;();
    private Thread cleanupThread;

    public ResourceManager() {
        // Start a daemon thread to check the reference queue regularly        cleanupThread = new Thread(() -&gt; {
            while (true) {
                try {
                    ResourceCleaner cleaner = (ResourceCleaner) ();
                    ();
                } catch (InterruptedException e) {
                    ().interrupt();
                    break;
                }
            }
        });
        (true);
        ();
    }

    public void registerResource(Resource resource) {
        ResourceCleaner cleaner = new ResourceCleaner(resource, queue);
        ("Resource registered: " + resource);
    }
}

Test code

public class ReferenceQueueExample {
    public static void main(String[] args) throws InterruptedException {
        ResourceManager manager = new ResourceManager();

        // Create a resource and register        Resource resource1 = new Resource("Resource-1");
        (resource1);

        // Simulation resources are no longer strongly cited        resource1 = null;

        // Trigger garbage collection        ();

        // Wait for a while to ensure that the garbage collection is completed        (1000);
    }
}

Running results

Resource created: Resource-1
Resource registered: Resource@1b6d3586
Cleaning up resource: Resource@1b6d3586

Summarize

By referencing the queue, we can track the recycling status of the object and perform a cleanup operation after the object is recycled. This mechanism is very suitable for use in resource management, cache cleaning and other scenarios. In practical applications, daemon threads can be used to regularly check the reference queue to ensure that the recycled resources are cleaned up in a timely manner.

This is the article about the detailed explanation of strong citations, soft citations, weak citations and virtual citations in Java. For more related content on Java strong citations, soft citations, weak citations and virtual citations, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!