Object reference in java

Keywords: jvm


In java, object references are divided into strong, soft, if and virtual references. Strong references are ordinary new objects. Soft references, weak references and virtual references are all inherited from the abstract class Reference.

1. Strong reference

The most common references in program code, such as person period = new person(), in any case, as long as the strong reference relationship is still in place and the strongly referenced objects are reachable, the garbage collector will not recycle the referenced objects.
If the strong reference relationship display is set to null, it may be recycled during garbage collection. The specific recycling time depends on the garbage collection strategy. It is precisely because as long as the strong reference relationship exists, it will not be GC. Therefore, strong reference is one of the main reasons for java memory leakage.
As long as the strong reference relationship remains, even if the program throws an OOM exception, the strongly referenced object will not be recycled.

for example

String str = new String("hello world");

The local variable str points to the String instance in the heap, which can be operated through str, so str is a strong reference to the String instance.

2. Soft reference

When the soft reference relationship exists, if the memory is insufficient, GC will recycle the garbage object. At this time, the soft reference object will not be recycled, because the soft reference relationship is still there, but after GC, the memory is still insufficient to allocate the object. At this time, the second GC will be performed, and the soft reference object will be recycled. If the memory is insufficient even if the soft reference object is recycled, Memory overflow occurs.
Soft references are used to describe objects that are useful but not necessary. For example, the cache uses soft references. If there is free memory, the cache can be reserved temporarily. When the memory is insufficient, the cache can be cleaned up to ensure that the program will not crash.

Example 1 is as follows

public static void main(String[] args) {
    /*persion Is a strong reference*/
    Persion persion = new Persion(1, "lzj", 30);
    /*Create a soft reference to the operation*/
    SoftReference<Persion> reference = new SoftReference<>(persion);
    /*Make the strong reference null for garbage collection*/
    persion = null;
    /*Gets the soft referenced object*/
    System.out.println(reference.get());	//Persion{id=1, name='lzj', age=30}
}

Example 2 is as follows:
Soft reference can also specify a reference queue when constructing a reference. When the soft reference associated objects are recycled, the recycled soft reference objects will be added to the specified reference queue. Through this queue, the recycling of soft reference associated objects can be tracked. Note that objects associated with soft references are recycled, and soft reference objects are added to the soft reference queue

public static void test2() throws InterruptedException {
    Persion persion = new Persion(1, "lzj", 30);
    ReferenceQueue<Persion> queue = new ReferenceQueue<>();
    SoftReference<Persion> reference = new SoftReference<>(persion, queue);
    System.out.println("Soft reference objects are:" + reference);
    /*Before garbage collection, the associated object of the object can be obtained through soft reference*/
    System.out.println(reference.get());
    persion = null;
    System.gc();
    Thread.sleep(1000);
    System.out.println(reference.get());

    /*After running, the code of this sentence is blocked all the time, which means that no soft reference related objects are recycled,
    * Call the remove method of the queue. When a soft reference associated object is recycled, the method will return, otherwise it will be blocked all the time*/
    Reference<? extends Persion> referenceGC = queue.remove();
    if (referenceGC == null){
        System.out.println("Description no GC,perhaps GC After, the memory space is still sufficient and the objects associated with soft references will not be recycled");
    }
}

The operation results are as follows:

Soft reference objects are: java.lang.ref.SoftReference@383534aa
Persion{id=1, name='lzj', age=30}
Persion{id=1, name='lzj', age=30}

3. Weak reference

Weak references are also used to represent some non essential objects. Objects associated with weak references can only survive until the next garbage collector occurs. When a GC occurs, objects associated with weak references are recycled regardless of whether the heap space memory is sufficient.
Weak references, like soft references, are very suitable for storing dispensable cache data. After using weak reference or soft reference, when the system memory is insufficient, these cached data will be recycled without memory overflow; When resources are sufficient, cached data can exist for a long time to improve program execution efficiency.

Example 1 is as follows:

public static void test1(){
    Persion persion = new Persion(1, "lzj", 30);
    WeakReference<Persion> reference = new WeakReference<>(persion);
    persion = null;
    System.out.println(reference.get());	//Persion{id=1, name='lzj', age=30}
}

Example 2 is as follows:
Like soft references, you can also specify a reference queue when constructing references. When the objects associated with weak references are recycled, the recycled weak reference objects will be added to the specified reference queue. Through this queue, you can track the recycling of weak reference associated objects. Note that objects associated with weak references are recycled, and weak reference objects are added to the weak reference queue

public static void test2() throws InterruptedException {
    Persion persion = new Persion(1, "lzj", 30);
    /*Weak reference queue for garbage collection*/
    ReferenceQueue<Persion> queue = new ReferenceQueue<>();
    WeakReference<Persion> reference = new WeakReference<>(persion, queue);
    System.out.println("Weak reference objects are:" + reference);
    persion = null;
    /*Before garbage collection, the pertion object associated with weak reference is not recycled and can be obtained*/
    System.out.println("Before garbage collection:" + reference.get());
    /*Enforce GC*/
    System.gc();
    /*The program sleeps for a period of time to execute GC*/
    Thread.sleep(1000);
    /*After garbage collection, the term object associated with the weak reference is recycled and cannot be obtained*/
    System.out.println("After garbage collection:" + reference.get());

    Reference<? extends Persion> persionGC;
    while ((persionGC = queue.remove()) != null){
        /*The sessiongc in the garbage pair is the previous reference weak reference object, and the reference is the weak reference to the period. It can be seen that the garbage collects the period object,
        * Note that the object associated with the recycled weak reference, that is, the period object
        * */
        System.out.println("Weak references recycled in garbage collection queue:" + persionGC);
        break;
    }
}

The output is as follows:

Weak reference objects are: java.lang.ref.WeakReference@74a14482
 Before garbage collection: Persion{id=1, name='lzj', age=30}
After garbage collection: null
 Weak references recycled in garbage collection queue: java.lang.ref.WeakReference@74a14482

4. Phantom reference

Virtual references, also known as ghost references or phantom references, are the weakest of reference types. If an object only holds virtual references, it is almost the same as internal references. As long as GC occurs, it will be recycled at any time. Therefore, whether an object holds a virtual reference will not determine the declaration cycle of the object at all.
Unlike the previous references, virtual applications cannot obtain the associated objects through the get method. The only purpose of setting the required Association for an object is to track the garbage collection process. For example, you can receive a system notification when this object is collected by the garbage collector. Since the virtual reference can track the object recycling time, some resource release operations can be placed in the virtual reference for execution and recording.

Another difference between virtual references and previous references is that virtual references must be used with reference queues. When the garbage collector prepares to recycle an object, if it finds that it still has a virtual reference, it will add the virtual reference to the reference queue after recycling the object, so as to inform the application of object recycling.

Examples are as follows

```java
public class PhantomReferenceDemo {
    public static Persion persion;
    public static ReferenceQueue<Persion> queue;
    
    public static void main(String[] args) {
        QueueThread queueThread = new QueueThread();
        /*Set the daemon thread. After the main thread ends, the queue thread ends automatically*/
        queueThread.setDaemon(true);
        queueThread.start();

        persion = new Persion(1, "lzj", 0);
        queue = new ReferenceQueue<>();
        PhantomReference<Persion> reference = new PhantomReference<>(persion, queue);
        persion = null;
        System.gc();
    }

    public static class QueueThread extends Thread{
        @Override
        public void run() {
            while (true){
                if (queue != null){
                    Reference<? extends Persion> gcObject = null;
                    try {
                        gcObject = queue.remove();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (gcObject != null){
                        System.out.println("GC When, gcObject The object associated with the virtual reference object was recycled");
                    }
                }
            }

        }
    }
}

5. Summary

Strong reference: if a reference relationship exists, it will become a valid object after reachability analysis, and it will not be recycled, even if OOM occurs;
Soft reference: when the memory is insufficient, recycle the associated objects of soft reference;
Weak reference: during GC, as long as a weak reference is found, the weak reference associated object is recycled;
Virtual reference: virtual reference is mainly used for object recycling and tracking.

Posted by nariman on Sun, 05 Sep 2021 11:19:11 -0700