Weak links removed atomically with placement in the link queue?

Is Java GC the weakest stage of atomic allocation of the weak referenceQueue link assigned to this link? In other words, if calling WeakReference.get () returns null, will WeakReference be in the queue?

+4
source share
2 answers

Allows you to parse Javadoc for WeakReference:

Assume that the garbage collector determines at some point in time when the object is poorly accessible.

At this time, it will atomize all weak links to this object and all weak links to any other unreachable objects from which this object is reached through a chain of strong and soft Recommendations.

, .

, .

, :

  • , .

  • WeakReference. WeakReference.get null.

  • .

  • WeakReference ( WeakReference ).

, WeakReference.get() null, , WeakReference.enqueue true ReferenceQueue.poll null.

. https://community.oracle.com/blogs/enicholas/2006/05/04/understanding-weak-references.

WeakReference null, , , WeakReference . , - : WeakHashMap, , deadWeakReferences.

ReferenceQueue . ReferenceQueueinto , , , , . ReferenceQueue .

, :

    public static class A {
}

public  static void main(String[] args) throws Exception{
    A a = new A();

    ReferenceQueue<A> rq = new ReferenceQueue<A>();
    WeakReference<A> aref = new WeakReference<A>(a, rq);    
    a = null;

    //aref.get() should be a, aref.isEnqueued() should return false, rq.poll() should return null
    System.out.println( "0: " + aref + " : " + aref.get() + " : " + aref.isEnqueued() + "  " + rq.poll() ); 

    Thread.sleep(1000);

    System.out.println("Running GC.");
    Runtime.getRuntime().gc();  //let GC clear aref
    System.out.println("GC ran.");

    //aref.get() should be null, aref.isEnqueued() should return false, rq.poll() should return null
    System.out.println( "1: " + aref + " : " + aref.get() + " " + aref.isEnqueued() + "  " + rq.poll()  );   

    //give some time for GC to enqueue aref
    Thread.sleep(1000);

    //ref.get() should be null, aref.isEnqueued() should return true, rq.poll() should return aref
    System.out.println( "2: " + aref + " : " + aref.get() + " " + aref.isEnqueued() + "  " + rq.poll() );  
}
+2

Java GC , ReferenceQueue, ?

. " " . .

, WeakReference.get() null, WeakReference ?

. , " ": .

0

Source: https://habr.com/ru/post/1692668/


All Articles