检索被引用对象的风格(WeakReference)

来源:互联网 发布:二手软件交易平台 编辑:程序博客网 时间:2024/06/03 16:56

Ref: http://blog.csdn.net/zhangzhaokun/article/details/5083415

BAD

obj = wr.get();

if (obj == null)

{

  wr= new WeakReference(recreateIt());  //1

  obj= wr.get();                        //2

}

//code that works with obj

行1之后,行2之前,有可能运行垃圾回收。若在行1之后执行了垃圾回收,通过recreateIt()创建的对象被回收,则行2中获得的对象将为null。


GOOD

obj = wr.get();

if (obj == null)

{

  obj= recreateIt();                    //1

  wr= new WeakReference(obj);           //2

}

//code that works with obj



原创粉丝点击