zoukankan      html  css  js  c++  java
  • Java SoftReference

    文章出处 http://blog.csdn.net/historyasamirror/article/details/6076505

    SoftReference的语义就是当内存不够用的时候,GC会回收SoftReference所引用的对象。所以,在memory sensitive的程序中将某些大型数据设置成SoftReference再合适不过了。 


    创建一个SoftReference: 

    Object obj = new Object();  
    SoftReference softRef = new SoftReference(obj);  
    obj = null;   

    最后那句“obj = null”很重要。如果不将obj设置成null,那么new出来的Object就会有一个"strong reference",如果这样,softRef就不能发挥作用了。 


    使用SoftReferene: 

    Object obj2;  
    obj2 = sr.get();  
    if (obj2 == null) // GC freed this  
    sr = new SoftReference(obj2 = new Object());   


    因为是SoftReference,所以有可能已经被GC回收了,所以需要判断sr.get()的返回值是否为null。如果是的话,就再重新new一个Object。这里的最后一行代码也很有讲究,比如,也许会这么写: 

    Object obj2;  
    obj2 = sr.get();  
    if (obj2 == null) {  
    sr = new SoftReference(new Object());  
    obj2 = sr.get();  
    }   

    这样的问题就在于GC可能发生在"sr = new SoftReference(new Object());"和"obj2 = sr.get()"之间,那么obj2仍然有可能为null。 


    如果想深入了解 可以移步这里 http://blog.csdn.net/ouyangtianhan/article/details/7221948

  • 相关阅读:
    子矩阵
    [Ahoi2008]Meet 紧急集合
    立体图
    CF933B A Determined Cleanup
    CF746G New Roads
    树的重量
    CF519E A and B and Lecture Rooms
    矩阵
    深入浅出乘法逆元
    20180519模拟赛T2——pretty
  • 原文地址:https://www.cnblogs.com/draem0507/p/3127181.html
Copyright © 2011-2022 走看看