[pre]String str=newString(" hello ");// ①
ReferenceQueue < String >rq=newReferenceQueue < String > ();// ②WeakReference < String >wf=newWeakReference < String > (str, rq);// ③
str =null;// ④取消"hello"对象的强引用String str1 = wf.get();// ⑤假如"hello"对象没有被回收,str1引用"hello"对象
// 假如"hello"对象没有被回收,rq.poll()返回nullReference <?extendsString >ref = rq.poll();// ⑥
[/pre] 在以上代码中,注意⑤⑥两处地方。假如“hello ”对象没有被回收 wf.get() 将返回“ hello ”字符串对象, rq.poll() 返回 null ;而加入“ hello ”对象已经被回收了,那么 wf.get() 返回 null , rq.poll() 返回 Reference 对象,但是此 Reference 对象中已经没有 str 对象的引用了 ( PhantomReference 则与WeakReference 、 SoftReference 不同 )。
引用机制与复杂数据结构的联合应用
了解了GC机制、引用机制,并配合上ReferenceQueue,我们就可以实现一些防止内存溢出的复杂数据类型。
例如,SoftReference具有构建Cache系统的特质,因此我们可以结合哈希表实现一个简单的缓存系统。这样既能保证能够尽可能多的缓存信息,又可以保证Java虚拟机不会因为内存泄露而抛出OutOfMemoryError。这种缓存机制特别适合于内存对象生命周期长,且生成内存对象的耗时比较长的情况,例如缓存列表封面图片等。对于一些生命周期较长,但是生成内存对象开销不大的情况,使用WeakReference能够达到更好的内存管理的效果。
附SoftHashmap的源码一份,相信看过之后,大家会对Reference机制的应用有更深入的理解。
[pre]packagecom. *** .widget;
// : SoftHashMap.javaimportjava.util. * ;
importjava.lang.ref. * ;
importandroid.util.Log;
publicclassSoftHashMapextendsAbstractMap{/**The internal HashMap that will hold the SoftReference.*/
privatefinalMap hash=newHashMap();/**The number of "hard" references to hold internally.*/
privatefinalintHARD_SIZE;/**The FIFO list of hard references, order of last access.*/
privatefinalLinkedList hardCache=newLinkedList();/**Reference queue for cleared SoftReference objects.*/
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/ruanjian/article-49607-4.html
不怕事
当年electricshock的精灵们回到曾经的森林去寻找回忆