博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
WeakReference与SoftReference
阅读量:4207 次
发布时间:2019-05-26

本文共 7094 字,大约阅读时间需要 23 分钟。

WeakReference与SoftReference都可以用来保存对象的实例引用,这两个类与垃圾回收有关。

WeakReference是弱引用,其中保存的对象实例可以被GC回收掉。这个类通常用于在某处保存对象引用,而又不干扰该对象被GC回收,通常用于Debug、内存监视工具等程序中。因为这类程序一般要求即要观察到对象,又不能影响该对象正常的GC过程。

最近在JDK的Proxy类的实现代码中也发现了Weakrefrence的应用,Proxy会把动态生成的Class实例暂存于一个由Weakrefrence构成的Map中作为Cache。

Implements a weak reference, which is the middle of the three types of references. Once the garbage collector decides that an object obj is is weakly-reachable, the following happens:

  • A set ref of references is determined. ref contains the following elements:
    • All weak references pointing to obj.
    • All weak references pointing to objects from which obj is either strongly or softly reachable.
  • All references in ref are atomically cleared.
  • All objects formerly being referenced by ref become eligible for finalization.
  • At some future point, all references in ref will be enqueued with their corresponding reference queues, if any.
Weak references are useful for mappings that should have their entries removed automatically once they are not referenced any more (from outside). The difference between a 
SoftReference
 and a 
WeakReference
 is the point of time at which the decision is made to clear and enqueue the reference:
  • SoftReference should be cleared and enqueued as late as possible, that is, in case the VM is in danger of running out of memory.
  • WeakReference may be cleared and enqueued as soon as is known to be weakly-referenced.

SoftReference是强引用,它保存的对象实例,除非JVM即将OutOfMemory,否则不会被GC回收。这个特性使得它特别适合设计对象Cache。对于Cache,我们希望被缓存的对象最好始终常驻内存,但是如果JVM内存吃紧,为了不发生OutOfMemoryError导致系统崩溃,必要的时候也允许JVM回收Cache的内存,待后续合适的时机再把数据重新Load到Cache中。这样可以系统设计得更具弹性。

A reference that is cleared when its referent is not strongly reachable and there is memory pressure.

Avoid Soft References for Caching

In practice, soft references are inefficient for caching. The runtime doesn't have enough information on which references to clear and which to keep. Most fatally, it doesn't know what to do when given the choice between clearing a soft reference and growing the heap.

The lack of information on the value to your application of each reference limits the usefulness of soft references. References that are cleared too early cause unnecessary work; those that are cleared too late waste memory.

Most applications should use an android.util.LruCache instead of soft references. LruCache has an effective eviction policy and lets the user tune how much memory is allotted.

Garbage Collection of Soft References

When the garbage collector encounters an object 
obj
 that is softly-reachable, the following happens:
  • A set refs of references is determined. refs contains the following elements:
    • All soft references pointing to obj.
    • All soft references pointing to objects from which obj is strongly reachable.
  • All references in refs are atomically cleared.
  • At the same time or some time in the future, all references in refs will be enqueued with their corresponding reference queues, if any.
The system may delay clearing and enqueueing soft references, yet all 
SoftReference
s pointing to softly reachable objects will be cleared before the runtime throws an 
.

Unlike a WeakReference, a SoftReference will not be cleared and enqueued until the runtime must reclaim memory to satisfy an allocation.

 

WeakReference的一个测试程序:

 

Java代码  
  1. import java.lang.ref.WeakReference;  
  2.   
  3. public class WeakReferenceTest {  
  4.   
  5.     /** 
  6.      * @param args 
  7.      */  
  8.     public static void main(String[] args) {  
  9.         A a = new A();  
  10.         a.str = "Hello, reference";  
  11.         WeakReference<A> weak = new WeakReference<A>(a);  
  12.         a = null;  
  13.         int i = 0;  
  14.         while (weak.get() != null) {  
  15.             System.out.println(String.format("Get str from object of WeakReference: %s, count: %d", weak.get().str, ++i));  
  16.             if (i % 10 == 0) {  
  17.                 System.gc();  
  18.                 System.out.println("System.gc() was invoked!");  
  19.             }  
  20.             try {  
  21.                 Thread.sleep(500);  
  22.             } catch (InterruptedException e) {  
  23.   
  24.             }  
  25.         }  
  26.         System.out.println("object a was cleared by JVM!");  
  27.     }  
  28.   
  29. }  

 程序运行结果:

 

Java代码  
  1. Get str from object of WeakReference: Hello, reference, count: 1  
  2. Get str from object of WeakReference: Hello, reference, count: 2  
  3. Get str from object of WeakReference: Hello, reference, count: 3  
  4. Get str from object of WeakReference: Hello, reference, count: 4  
  5. Get str from object of WeakReference: Hello, reference, count: 5  
  6. Get str from object of WeakReference: Hello, reference, count: 6  
  7. Get str from object of WeakReference: Hello, reference, count: 7  
  8. Get str from object of WeakReference: Hello, reference, count: 8  
  9. Get str from object of WeakReference: Hello, reference, count: 9  
  10. Get str from object of WeakReference: Hello, reference, count: 10  
  11. System.gc() was invoked!  
  12. object a was cleared by JVM!  
 

SoftReference的一个测试程序:

 

Java代码  
  1. import java.lang.ref.SoftReference;  
  2.   
  3. public class SoftReferenceTest {  
  4.   
  5.     /** 
  6.      * @param args 
  7.      */  
  8.     public static void main(String[] args) {  
  9.         A a = new A();  
  10.         a.str = "Hello, reference";  
  11.         SoftReference<A> sr = new SoftReference<A>(a);  
  12.         a = null;  
  13.         int i = 0;  
  14.         while (sr.get() != null) {  
  15.             System.out.println(String.format("Get str from object of SoftReference: %s, count: %d", sr.get().str, ++i));  
  16.             if (i % 10 == 0) {  
  17.                 System.gc();  
  18.                 System.out.println("System.gc() was invoked!");  
  19.             }  
  20.             try {  
  21.                 Thread.sleep(500);  
  22.             } catch (InterruptedException e) {  
  23.   
  24.             }  
  25.         }  
  26.         System.out.println("object a was cleared by JVM!");  
  27.     }  
  28.   
  29. }  

 程序运行结果:

 

Java代码  
  1. Get str from object of SoftReference: Hello, reference, count: 1  
  2. Get str from object of SoftReference: Hello, reference, count: 2  
  3. Get str from object of SoftReference: Hello, reference, count: 3  
  4. Get str from object of SoftReference: Hello, reference, count: 4  
  5. Get str from object of SoftReference: Hello, reference, count: 5  
  6. Get str from object of SoftReference: Hello, reference, count: 6  
  7. Get str from object of SoftReference: Hello, reference, count: 7  
  8. Get str from object of SoftReference: Hello, reference, count: 8  
  9. Get str from object of SoftReference: Hello, reference, count: 9  
  10. Get str from object of SoftReference: Hello, reference, count: 10  
  11. System.gc() was invoked!  
  12. Get str from object of SoftReference: Hello, reference, count: 11  
  13. Get str from object of SoftReference: Hello, reference, count: 12  
  14. Get str from object of SoftReference: Hello, reference, count: 13  
  15. Get str from object of SoftReference: Hello, reference, count: 14  
  16. Get str from object of SoftReference: Hello, reference, count: 15  
  17. Get str from object of SoftReference: Hello, reference, count: 16  
  18. Get str from object of SoftReference: Hello, reference, count: 17  
  19. Get str from object of SoftReference: Hello, reference, count: 18  
  20. Get str from object of SoftReference: Hello, reference, count: 19  
  21. Get str from object of SoftReference: Hello, reference, count: 20  
  22. System.gc() was invoked!  
  23. Get str from object of SoftReference: Hello, reference, count: 21  
  24. Get str from object of SoftReference: Hello, reference, count: 22  
  25. Get str from object of SoftReference: Hello, reference, count: 23  
  26. Get str from object of SoftReference: Hello, reference, count: 24  
  27. Get str from object of SoftReference: Hello, reference, count: 25  
  28. Get str from object of SoftReference: Hello, reference, count: 26  
  29. Get str from object of SoftReference: Hello, reference, count: 27  
  30. Get str from object of SoftReference: Hello, reference, count: 28  

转载地址:http://allli.baihongyu.com/

你可能感兴趣的文章
adb常用命令
查看>>
通过LR监控Linux服务器性能
查看>>
通过FTP服务的winsockes录制脚本
查看>>
LRwinsocket协议测试AAA服务器
查看>>
Net远程管理实验
查看>>
反病毒专家谈虚拟机技术 面临两大技术难题
查看>>
几种典型的反病毒技术:特征码技术、覆盖法技术等
查看>>
性能测试一般过程与LR性能测试过程
查看>>
Software Security Testing软件安全测试
查看>>
SQL注入漏洞全接触--进阶篇
查看>>
SQL注入漏洞全接触--高级篇
查看>>
SQL注入法攻击一日通
查看>>
论文浅尝 | 通过共享表示和结构化预测进行事件和事件时序关系的联合抽取
查看>>
论文浅尝 | 融合多粒度信息和外部语言知识的中文关系抽取
查看>>
论文浅尝 | GMNN: Graph Markov Neural Networks
查看>>
廖雪峰Python教程 学习笔记3 hello.py
查看>>
从内核看epoll的实现(基于5.9.9)
查看>>
python与正则表达式
查看>>
安装.Net Framework 4.7.2时出现“不受信任提供程序信任的根证书中终止”的解决方法
查看>>
input type=“button“与input type=“submit“的区别
查看>>