Reference details

1 Overview

The picture is quoted from https://blog.csdn.net/u011801189/article/details/52723868

According to the annotations in the Reference class, the entire Reference inheritance system is closely linked with GC . When the Reference object is processed by the GC , it means that the object pointed to by the Reference has been recycled, then the Reference object should also be processed accordingly ; if the Reference object is registered with a ReferenceQueue , then it will be thrown into the corresponding ReferenceQueue for recycling.

Note from the above figure that when Reference objects are in the Reference.pending queue, they use this member variable to complete the connection of the queue;discovered 

This Reference object is in an active state, indicating that the object pointed to by this Reference has not become garbage and has not been GCed . This Reference object has not yet entered the Reference world, it is still under the monitoring of the GC ; when it is garbage collected, that is, after entering the Reference world, this discoveredfield is reused as the connection of the linked list, and the next pointer is not applicable at this time. , just point next to this .

When the Reference object is actually put into the ReferenceQueue it is registered , the next pointer is used to connect to the queue; discoveredthe field is set to null at this time .

2. Reference applicable scenarios

. Soft references are generally used in some memory-sensitive applications for cache use. Soft referenced objects will be reclaimed before the JVM throws an OutOfMemoryError . This feature of it makes it most suitable as a cache within a process. 

Weak references are generally used to save some information that is the same as the object life cycle. Once these objects are garbage collected, we can recycle these objects. How is this done? Basically, it is related to the functions provided by Reference . Looking at the constructor of Reference , you will find that it requires a ReferenceQueue to be passed in, and this Queue is to provide a mechanism that allows programmers to be notified before the object is garbage collected, and make some business logic . This mechanism makes up for the inadequacy of the JVM 's finalizer mechanism. Because the finalizer mechanism of the JVM does not guarantee that the finalizer will be called, the logic that we hope that an object's related resources will be released after the end of its life cycle cannot be guaranteed. And it is said (for confirmation) that the finalizer is implemented through JNI , and the overhead of calling through the JVM is relatively large. The JVM provides programmers with another way to deal with resource recycling by providing this Reference mechanism. 

lVirtual  references can also provide a notification mechanism when such objects are garbage collected. The only difference from the above two is that the get method of PhantomReference is implemented to always return null . This means that when you get the notification of PhantomReference through ReferenceQueue , you can no longer make a strong reference to it, and you can only make your own cleanup logic. This also shows that the PhantomReference is pre-mortem , which means it is before the real finalize . If the object itself can be obtained through the get method, and then a strong reference to it is established, an error will occur during subsequent garbage collection processing. So simply don't let the programmer get a reference to the object here. And SoftReference and WeakReference should be after the finalize mechanism of JVM .

 

When I was eating today, I thought of a problem, that is PhantomReference, its getmethod returns null . If this is the case, even if I can get this through the method, I still can't do real resource recovery for this object. So what should we do to recycle the resources associated with it?ReferenceQueuePhantomReferencereferent

publicclassLargeObjectFinalizerextendsPhantomReference<Object> {

 

    publicLargeObjectFinalizer(

      Object referent, ReferenceQueue<? super Object> q) {

        super(referent, q);

    }

 

    public void finalizeResources () {

        // free resources

        System.out.println("clearing ...");

    }

}

Then, using this LargeObjectFinalizerassociation to ourreferent

ReferenceQueue<Object>referenceQueue = new ReferenceQueue<>();

List<LargeObjectFinalizer>references = new ArrayList<>();

List<Object>largeObjects = new ArrayList<>();

 

for (int i = 0; i < 10; ++i) {

    Object largeObject = new Object();

    largeObjects.add(largeObject);

    references.add(new LargeObjectFinalizer(largeObject,referenceQueue));

}

 

largeObjects= null;

System.gc();

 

Reference<?>referenceFromQueue;

for(PhantomReference<Object> reference : references) {

    System.out.println(reference.isEnqueued());

}

 

while((referenceFromQueue = referenceQueue.poll()) != null) {

    ((LargeObjectFinalizer)referenceFromQueue).finalizeResources();

    referenceFromQueue.clear();

}

The example above is simple, but enough to illustrate the point, when garbage collection works, it puts ours on top LargeObjectFinalizerof the one we provide referenceQueue, and then we remove ours from it LargeObjectFinalizer, calling the resource recovery method finalizeResources.

I think this is PhantomReferencea typical example of using garbage collection. We do not use it directly PhantomReference, but by extending it, associate the object we want to pay attention to, such as here Object, and some resources associated with the object, to ours LargeObjectFinalizer, of course, this is the constructor that needs to be modified, or It is related to this in some other way LargeObjectFinalizer. Only in this way can we ReferenceQueueachieve the purpose of garbage collection through this mechanism.

 

3.     StrongReference、SoftReference,WeakReference、PhantomReference

 Strong reference  >   Soft reference  >   Weak reference  >   Phantom reference

Strong reference ( StrongReference ) Strong reference is the most commonly used reference. If an object has a strong reference, the garbage collector will never collect it. When the memory space is insufficient, the Java virtual machine would rather throw an OutOfMemoryError error to cause the program to terminate abnormally, rather than solve the problem of insufficient memory by arbitrarily reclaiming objects with strong references.
   

( 2 ) Soft reference ( SoftReference )

    If an object has only soft references, the memory space is sufficient, and the garbage collector will not reclaim it; if the memory space is insufficient, the memory of these objects will be reclaimed. The object can be used by the program as long as it is not collected by the garbage collector. Soft references can be used to implement memory-sensitive caches.

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

(3) Weak reference ( WeakReference )

    The difference between weak references and soft references is that objects with only weak references have a shorter lifetime. In the process of scanning the memory area under the jurisdiction of the garbage collector thread, once an object with only weak references is found, its memory will be reclaimed regardless of whether the current memory space is sufficient or not. However, since the garbage collector is a very low-priority thread, objects that only have weak references will not necessarily be discovered 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 associated reference queue.

virtual reference ( PhantomReference )

    " Virtual reference " , as the name suggests, is just in name only. Unlike other references, virtual reference does not determine the life cycle of an object. If an object only holds phantom references, then it can be collected by the garbage collector at any time as if it had no references at all.

    Phantom references are primarily used to track the activity of objects being reclaimed by the garbage collector. One difference between virtual references and soft references and weak references is that virtual references must be used in conjunction with reference queues ( ReferenceQueue ). When the garbage collector is ready to reclaim 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 reclaiming the memory of the object.

 

Because references and memory reclamation are closely related. Below, we first have an understanding of memory recycling through examples; then, we will further deepen our understanding of references through reference examples.

 

 


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324729641&siteId=291194637