SoftReference、WeakReference、PhantomRefrence分析和比较
|
级别 |
什么时候被垃圾回收 |
用途 |
生存时间 |
|
强引用 |
从来不会 |
对象的一般状态 |
JVM停止运行时终止 |
|
软引用 |
在内存不足时 |
优化内存使用 |
内存不足时终止 |
|
弱引用 |
在垃圾回收时 |
对象缓存 |
gc运行后终止 |
|
虚引用 |
|
软引用、弱引用测试
/**
* cd /Users/gl/IntelliJProjects/JBase/jdk/build/classes/main
* java -Xms20M -Xmx20M -Xmn5M reference.TestReference
*/
public class TestReference { private static int K = 1024; private static int M = 1024 * K; public static void main(String[] args) {
testSoftReference();
testWeakReference();
} /**
java.lang.ref.SoftReference@610455d6
null
java.lang.ref.SoftReference@610455d6 代码`byte[] c = new byte[5 * M];` 会导致内存溢出, 但是在溢出前会进行GC,
所以`softReference.get()`会返回`null`(被软引用对象引用的`b`被回收了), 并且应用对象`softReference`会被加入引用队列. */
private static void testSoftReference(){
byte[] a = new byte[10 * M];
byte[] b = new byte[2 * M];
ReferenceQueue queue = new ReferenceQueue();
SoftReference softReference = new SoftReference(b, queue);
System.out.println(softReference);
b = null;
try {
byte[] c = new byte[5 * M];
}catch (Error error){
System.out.println(softReference.get());
//SoftReference被加入引用队列
System.out.println(queue.poll());
}
} /**
[B@4e25154f
null *在垃圾回收器线程扫描它所管辖的内存区域的过程中,一旦发现了只具有弱引用的对象,不管当前内存空间足够与否,都会回收它的内存。
* 不过,由于垃圾回收器是一个优先级很低的线程,因此不一定会很快发现那些只具有弱引用的对象。
*/
private static void testWeakReference(){
byte[] a = new byte[10 * M];
ReferenceQueue queue = new ReferenceQueue();
WeakReference weakReference = new WeakReference(a, queue);
a = null;
System.out.println(weakReference.get());
System.gc();
System.out.println(weakReference.get());
}
}
使用SoftReference优化内存
//创建Image对象
Image image = new Image();
…
//使用 image
…
//使用完了image,将它设置为soft 引用类型,并且释放强引用
SoftReference sr = new SoftReference(image);
image = null;
…
//下次使用时
if (sr != null) {
image = sr.get();
}else{
//低内存,GC,释放image,因此需要重新装载
image = new Image();
sr = new SoftReference(image);
}
理解
虚引用”顾名思义,就是形同虚设,与其他几种引用都不同,虚引用并不会决定对象的生命周期。如果一个对象仅持有虚引用,那么它就和没有任何引用一样,
在任何时候都可能被垃圾回收器回收。虚引用主要用来跟踪对象被垃圾回收器回收的活动。
为了确保可回收对象保持原样,无法检索虚引用的值:虚幻引用的get方法始终返回null。
Phantom reference objects, which are enqueued after the collector determines that their referents may otherwise be reclaimed. Phantom references are
most often used for scheduling pre-mortem cleanup actions in a more flexible way than is possible with the Java finalization mechanism.
If the garbage collector determines at a certain point in time that the referent of a phantom reference is phantom reachable, then at that time or at some
later time it will enqueue the reference.
In order to ensure that a reclaimable object remains so, the referent of a phantom reference may not be retrieved: The get method of a phantom
reference always returns null.
Unlike soft and weak references, phantom references are not automatically cleared by the garbage collector as they are enqueued. An object that is
reachable via phantom references will remain so until all such references are cleared or themselves become unreachable.
PhantomReference 有两个好处:
它可以让我们准确地知道对象何时被从内存中删除
这个特性可以被用于一些特殊的需求中(例如 Distributed GC, XWork 和 google-guice 中也使用 PhantomReference 做了一些清理性工作).
它可以避免 finalization 带来的一些根本性问题。
上文提到 PhantomReference 的唯一作用就是跟踪 referent 何时GC, 但是 WeakReference 也有对应的功能, 两者的区别到底在哪呢 ?
这就要说到 Object 的 finalize 方法, 此方法将在 gc 执行前被调用, 如果某个对象重载了 finalize 方法并故意在方法内创建本身的强引用,
这 GC 无法回收这个对象并有可能引起任意次 GC, 最后的结果就是明明 JVM 内有很多 Garbage 却 OutOfMemory, 使用 PhantomReference
就可以避免这个问题, 因为 PhantomReference 是在 finalize 方法执行后回收的,也就意味着此时已经不可能拿到原来的引用, 也就不会出现上述问题,
当然这是一个很极端的例子, 一般不会出现.
/**
*
* 相当于
* Object o = new Object();
* o = null;
*/
private static void testPhantomReference(){
ReferenceQueue queue = new ReferenceQueue();
PhantomReference ref = new PhantomReference(new Object(), queue);
System.out.println(ref.get()); }
参考:
SoftReference、WeakReference、PhantomRefrence分析和比较的更多相关文章
- Java之引用类型分析(SoftReference/WeakReference/PhantomReference)
引言: 即使对于Java的很多老鸟来说,如果忽然问他引用的类型,大概率是一脸茫然,不知所措的-.Java中的引用还分类型,神马情况??? 本文将针对这些类型进行分析,帮助您一文知所有类型. Java的 ...
- Java核心技术-高级特性(2)- SoftReference, WeakReference and PhantomReference
Java.lang.ref 是 Java 类库中比较特殊的一个包,它提供了与 Java 垃圾回收器密切相关的引用类.这些引用类对象可以指向其它对象,但它们不同于一般的引用,因为它们的存在并不防碍 Ja ...
- Softreference | WeakReference
转自:http://blog.csdn.net/kavendb/article/details/5935577 本文介绍对象的强.软.弱和虚引用的概念.应用及其在UML中的表示. 1.对象的强.软.弱 ...
- Reference SoftReference WeakReference PhantomReference Cleaner 的研究与实践
最近在看netty的时候看到直接内存的相关概念,为了更详细的了解一下具体原理,搜到了一篇不错的文章 http://lovestblog.cn/blog/2015/05/12/direct-buffer ...
- java SoftReference WeakReference
Java 2 平台引入了 java.lang.ref 包,其中包括的类可以让您引用对象,而不将它们留在内存中.这些类还提供了与垃圾收集器(garbage collector)之间有限的交互. 1.先“ ...
- Threadlocal源码分析以及其中WeakReference作用分析
今天在看Spring 3.x企业应用开发实战,第九章 Spring的事务管理,9.2.2节ThreadLocal的接口方法时,书上有提到Threadlocal的简单实现,我就去看了下JDK1.8的Th ...
- 4种引用与垃圾回收 :StrongReference, SoftReference, WeakReference , PhantomReference
- Java/Android引用类型及其使用分析
Java/Android中有四种引用类型,分别是: Strong reference - 强引用Soft Reference - 软引用Weak Reference - ...
- Java 引用 WeakReference
Reference 是一个抽象类,而 SoftReference,WeakReference,PhantomReference 以及 FinalReference 都是继承它的具体类.接下来我们来分别 ...
随机推荐
- java strtus2 拦截器(Interceptors)
在strtus2 中有一个比较重要的东西就是拦截器(Interceptors) 拦截器可以做到在已有的业务中插入一块共通的,比如在一个业务中,直接插入一串登录功能,就不用去每个页面一个个去显示是否登录 ...
- 组建一台计算机5_硬件5 多位存储器&累加器&初始汇编(1)
转载请遵循GNU开源宣言.Copyleft ! <2013>, <http://www.cnblogs.com/sciencefans from buaa 华罗庚班> 阅读此文 ...
- 查看、分析memcached使用状态
访问量上升,数据库压力大,怎么办?好办法是在中间挡一层缓存!这个缓存要求高效,不能比数据库慢,否则服务质量受影响:如果能把数据用hash打散存储到硬盘,也是可以的,不过在内存越来越便宜的今天,还是使用 ...
- Entity Framework(四):使用DbModelBuilder API创建表结构
DbContext类有一个OnModelCreating方法,它用于流利地配置领域类到数据库模式的映射.下面我们以fluent API的方式来定义映射.首先,先将Product类注释掉,重新编写该类, ...
- crontab中运行python程序出错,提示ImportError: No module named解决全过程
将一个python脚本放入crontab执行时,提示如下错:ImportError: No module named hashlib但是在shell中直接执行时没有任何问题,google之后,得到线索 ...
- Linux系统下如何查看物理内存占用率
Linux系统下如何查看物理内存占用率 Linux下看内存和CPU使用率一般都用top命令,但是实际在用的时候,用top查看出来的内存占用率都非常高,如:Mem: 4086496k total, ...
- Python安装相关的机器学习库以及图像处理库
安装 sudo apt-get install python-scipy sudo apt-get install python-numpy sudo apt-get install python-m ...
- KVC/KVO之KVO
本章将分为三个部分: KVO是什么 KVO有什么用 KVO例子 KVO是什么 KVO,即NSKeyValueObserving,一个非正式的Protocol,提供一种机制来间接观察其他对象属性的变化. ...
- VC++ GetSafeHwnd用法
GetSafeHwnd HWND GetSafeHwnd() const; 当我们想得到一个窗口对象(CWnd的派生对象)指针的句柄(HWND)时,最安全的方法是使用GetSafeHwnd()函数. ...
- hdu 3905(dp)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3905 思路:dp[i][j]表示前i分钟,睡了j分钟收获的的最大价值,并记tmp_dp[i][j]为从 ...