Java virtual queues and references cited

One o'clock eye

Reference queues represented by ReferenceQueue class, which holds a reference to the object is recovered. When used in combination a soft, weak, and references cited queue, the recovery system after the object is referenced, it will be recovered to add a reference corresponding to the object reference associated queue. Virtual reference before the object is released, it will add a reference to the corresponding virtual queue associated with its reference, so that action can be taken before the object is recovered.

Phantom reference objects can not get it corresponds.

Two combat

Code 1

import java.lang.ref.*;

public class PhantomReferenceTest
{
   public static void main(String[] args)
      throws Exception
   {
      // 创建一个字符串对象
      String str = new String("疯狂Java讲义");
      // 创建一个引用队列
      ReferenceQueue rq = new ReferenceQueue();
      // 创建一个虚引用,让此虚引用引用到"疯狂Java讲义"字符串
      PhantomReference pr = new PhantomReference (str , rq);
      // 切断str引用和"疯狂Java讲义"字符串之间的引用
      str = null;
      // 取出虚引用所引用的对象,并不能通过虚引用获取被引用的对象,所以此处输出null
      System.out.println(pr.get());  //①
      // 强制垃圾回收
      System.gc();
      System.runFinalization();
      // 垃圾回收之后,虚引用将被放入引用队列中
      // 取出引用队列中最先进入队列中的引用与pr进行比较
      System.out.println(rq.poll() == pr);   //②
   }
}

2 runs

null
true

3 Description

Avoid using the reference class during program execution objects remain in memory. If the method of soft, weak, or imaginary references cited reference object, the garbage collector can freely release the object. If you want to minimize the program in its life cycle, the memory occupied by the size of these reference class is very good.

Guess you like

Origin blog.csdn.net/chengqiuming/article/details/93383592