Reference reference class

  • WeakReference

Weak reference objects, which do not prevent their referents from being made finalizable, finalized, and then reclaimed. 
Weak references are most often used to implement canonicalizing mappings. Suppose that the garbage collector determines at a certain point in time that an object is weakly reachable.
At that time it will atomically clear all weak references to that object and all weak references to any other
weakly
-reachable objects from which that object is reachable through a chain of strong and soft references.
At the same time it will declare all of the formerly weakly-reachable objects to be finalizable.
At the same time or at some later time it will enqueue those newly-cleared weak references that are registered with reference queues. Since: 1.2

Translation:

Weak reference objects, which do not prevent be terminated, termination and recovery of their reference objects . Weak references are most often used to implement the mapping.
Assume that the garbage collector determines at a certain point in time the object is weakly reachable, it will automatically clear all weak references to that object, and all weak references to other weak up objects, these objects are available through a series of strong references and soft references reach from the object. At the same time, it will declare all objects are available before the end of the weak.

At the same time or later it will add those new Clear labeling weak reference to the reference queue (Reference Queue) in .

Constructor Summary:

WeakReference​(T referent)    
WeakReference​(T referent, ReferenceQueue<? super T> q)    

Description:

For objects only weak references, as long as a garbage collection operation, regardless of the JVM memory is not enough, will reclaim the memory occupied by the object. Object reference can be obtained by the get () method.

Example:

 public static void main(String[] args) {
        Object o1 = new Object();
        WeakReference<Object> weakReference = new WeakReference<>(o1);
        System.out.println("------回收前------");
        System.out.println("o1:"+o1);
        System.out.println("weakReference:"+weakReference.get());

        o1 = null;
        System.gc();
        System.out.println("------回收后------");
        System.out.println("o1:"+ O1);
        System.out.println("weakReference:"+weakReference.get());
        

    }

result:

Prior to recovery ------ ------ 
O1: java.lang.Object@4554617c 
java.lang.Object@4554617c: WeakReference
 after recovery ------ ------ 
O1: null 
WeakReference : null 

Process Finished with Exit code 0

 

 

 

Guess you like

Origin www.cnblogs.com/kongieg/p/11893335.html