强引用,弱引用,软引用,虚引用
2016-03-11 19:30
204 查看
强引用
强引用是我们在编程过程中使用的最简单的引用,如代码String s=”abc”中变量s就是字符串对象”abc”的一个强引用。任何被强引用指向的对象都不能被垃圾回收器回收,这些对象都是在程序中需要的。弱引用
Counter counter = new Counter(); // strong reference WeakReference<Counter> weakCounter = new WeakReference<Counter>(counter); //weak reference counter = null; // now Counter object is eligible for garbage collection
现在只要你给强引用对象counter赋空值null,该对象就可以被垃圾回收器回收。因为该对象此时不再含有其他强引用,即使指向该对象的弱引用weakCounter也无法阻止垃圾回收器对该对象的回收。
如果一个对象只有弱引用指向它,垃圾回收器会立即回收该对象,这是一种急切回收方式
软引用
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 line 2 prime = null; // now Counter object is eligible for garbage collection but only be collected when JVM absolutely needs memory
强引用置空之后,代码的第二行为对象Counter创建了一个软引用,该引用同样不能阻止垃圾回收器回收对象,但是可以延迟回收,与弱引用中急切回收对象不同。
强引用置空之后,代码的第二行为对象Counter创建了一个软引用,该引用同样不能阻止垃圾回收器回收对象,但是可以延迟回收,与弱引用中急切回收对象不同。鉴于软引用和弱引用的这一区别,软引用更适用于缓存机制,而弱引用更适用于存贮元数据。
如果有软引用指向这些对象,则只有在JVM需要内存时才回收这些对象。
虚引用
DigitalCounter digit = new DigitalCounter(); // digit reference variable has strong reference – line 3 PhantomReference phantom = new PhantomReference(digit); // phantom reference to object created at line 3 digit = null;
对象可以在任何时候被垃圾回收器回收,一旦移除强引用,第三行的DigitalCounter对象可以在任何时候被垃圾回收器回收。因为只有一个虚引用指向该对象,而虚引用无法阻止垃圾回收器回收对象。
相关文章推荐
- 实验0、了解和熟悉操作系统实验
- C++ Primer Plus学习:第五章
- 单片机学习之路
- 《剑指offer》——正则表达式匹配
- 基因数据处理5之GRCH38数据源和查看信息
- 第二周学习进度情况
- 在 tornado 中异步无阻塞的执行耗时任务
- Fibonacci数
- Java自定义类数组的创建和使用
- HttpClient4.5教程-第三章-HTTP状态管理
- 在maven中安装oracle11g驱动
- BZOJ 1051 受欢迎的牛
- private,public,protected 的作用
- android onSaveInstanceState方法
- django no module splite3的问题
- PHP 对于 MYSQL 基础操作
- A. Again Twenty Five!
- 梳理
- 学习进度条
- C++ Primer Plus学习:第四章