(counter); //weak referencecounter = null; // now Counter object is eligible for garbage collection现在只要你给强引⽤对象counter赋空值null,该对象就可以被垃圾回收器回收。因为该对象此时不再含有其他强引⽤,即使指向该对象的弱引⽤weakCounter也⽆法阻⽌垃圾回收器对该对象的回收。相反的,如果该对象含有软引⽤,Counter对象不会⽴即被回收,除⾮JVM需要内存。Java中的软引⽤使⽤java.lang.ref.SoftReference类来表⽰,你可以使⽤如下代码创建软引⽤:
复制代码 代码如下:
Counter prime = new Counter(); // prime holds a strong reference – line 2
SoftReference soft = new SoftReference(prime) ; //soft reference variable has SoftReference to Counter Object created at line2
prime = null; // now Counter object is eligible for garbage collection but only be collected when JVM absolutely needsmemory
强引⽤置空之后,代码的第⼆⾏为对象Counter创建了⼀个软引⽤,该引⽤同样不能阻⽌垃圾回收器回收对象,但是可以延迟回收,与弱引⽤中急切回收对象不同。鉴于软引⽤和弱引⽤的这⼀区别,软引⽤更适⽤于缓存机制,⽽弱引⽤更适⽤于存贮元数据。另⼀个使⽤弱引⽤的例⼦是WeakHashMap,它是除HashMap和TreeMap之外,Map接⼝的另⼀种实现。
WeakHashMap有⼀个特点:map中的键值(keys)都被封装成弱引⽤,也就是说⼀旦强引⽤被删除,WeakHashMap内部的弱引⽤就⽆法阻⽌该对象被垃圾回收器回收。
虚引⽤是java.lang.ref package包中第三种可⽤的引⽤,使⽤java.lang.ref.PhantomReference类来表⽰。拥有虚引⽤的对象可以在任何时候被垃圾回收器回收。和弱引⽤和软引⽤相似,你可以通过如下代码创建虚引⽤:复制代码 代码如下:
DigitalCounter digit = new DigitalCounter(); // digit reference variable has strong reference – line 3
PhantomReference phantom = new PhantomReference(digit); // phantom reference to object created at line 3digit = null;
⼀旦移除强引⽤,第三⾏的DigitalCounter对象可以在任何时候被垃圾回收器回收。因为只有⼀个虚引⽤指向该对象,⽽虚引⽤⽆法阻⽌垃圾回收器回收对象。
除了了解弱引⽤、软引⽤、虚引⽤和WeakHashMap,还需要了解ReferenceQueue。在创建任何弱引⽤、软引⽤和虚引⽤的过程中你可以通过如下代码提供引⽤队列ReferenceQueue:
复制代码 代码如下:
ReferenceQueue refQueue = new ReferenceQueue(); //reference will be stored in this queue for cleanupDigitalCounter digit = new DigitalCounter();
PhantomReference phantom = new PhantomReference(digit, refQueue);引⽤实例被添加在引⽤队列中,你可以再任何时候通过查询引⽤队列回收对象。⼀个对象的⽣命周期可以通过下图进⾏描述:
这就是Java中弱引⽤和软引⽤的区别。我们还学到了⼀些基本的引⽤类:弱引⽤、软引⽤、虚引⽤以及WeakHashMap和WeakHashMap。总之,合理的使⽤引⽤可以帮助垃圾回收器更好的管理Java内存。