WeakReference and SoftReference were added into Java API from long time but not every Java programmer is familiar with it. Which means there is a gap between where and how to use WeakReference and SoftReference in Java. Reference classes are particularly important in context of How Garbage collection works. As we all know that Garbage Collector reclaims memory from objects which are eligible for garbage collection, but not many programmer knows that this eligibility is decided based upon which kind of references are pointing to that object. This is also main difference between WeakReference and SoftReference in Java. Garbage collector can collect an object if only weak references are pointing towards it and they are eagerly collected, on the other hand Objects with SoftReference are collected when JVM absolutely needs memory. These special behaviour of SoftReference and WeakReference makes them useful in certain cases e.g. SoftReference looks perfect for implementing caches, so when JVM needs memory it removes object which have only SoftReference pointing towards them. On the other hand WeakReference is great for storing meta data e.g. storing ClassLoader reference. If no class is loaded then no point in keeping reference of ClassLoader, a WeakReference makes ClassLoader eligible for Garbage collection as soon as last strong reference removed. In this article we will explore some more about various reference in Java e.g. Strong reference and Phantom reference.
WeakReference vs SoftReference in Java
For those who don't know there are four kind of reference in Java :
- Strong reference
- Weak Reference
- Soft Reference
- Phantom Reference
Strong Reference is most simple as we use it in our day to day programming life e.g. in the code, String s = "abc" , reference variable s has strong reference to String object "abc". Any object which has Strong reference attached to it is not eligible for garbage collection. Obviously these are objects which is needed by Java program. Weak Reference are represented using java.lang.ref.WeakReference class and you can create Weak Reference by using following code :
Counter counter = new Counter(); // strong reference - line 1 WeakReference<Counter> weakCounter = new WeakReference<Counter>(counter); // weak // reference counter = null; // now Counter object is eligible for garbage collection
Now as soon as you make strong reference counter = null, counter object created on line 1 becomes eligible for garbage collection; because it doesn't have any more Strong reference and Weak reference by reference variable weakCounter can not prevent Counter object from being garbage collected. On the other hand, had this been Soft Reference, Counter object is not garbage collected until JVM absolutely needs memory. Soft reference in Java is represented using java.lang.ref.SoftReference class. You can use following code to create a SoftReference in Java
Counter prime = new Counter(); // prime holds a strong reference - line 2 SoftReference<Counter> soft = new SoftReference<Counter>(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
After making strong reference null, Counter object created on line 2 only has one soft reference which can not prevent it from being garbage collected but it can delay collection, which is eager in case of WeakReference. Due to this major difference between SoftReference and WeakReference, SoftReference are more suitable for caches and WeakReference are more suitable for storing meta data. One convenient example of WeakReference is WeakHashMap, which is another implementation of Map interface like HashMap or TreeMap but with one unique feature. WeakHashMap wraps keys as WeakReference which means once strong reference to actual object removed, WeakReference present internally on WeakHashMap doesn't prevent them from being Garbage collected.
Phantom reference is third kind of reference type available in java.lang.ref package. Phantom reference is represented by java.lang.ref.PhantomReference class. Object which only has Phantom reference pointing them can be collected whenever Garbage Collector likes it. Similar to WeakReference and SoftReference you can create PhantomReference by using following code :
DigitalCounter digit = new DigitalCounter(); // digit reference variable has strong reference - line 3 PhantomReference<DigitalCounter> phantom = new PhantomReference<DigitalCounter>(digit); // phantom reference to object created at line 3 digit = null;
As soon as you remove Strong reference, DigitalCounter object created at line 3 can be garbage collected at any time as it only has one more PhantomReference pointing towards it, which can not prevent it from GC'd.
Apart from knowing about WeakReference, SoftReference, PhantomReference and WeakHashMap there is one more class called ReferenceQueue which is worth knowing. You can supply a ReferenceQueue instance while creating any WeakReference, SoftReference or PhantomReference as shown in following code :
ReferenceQueue refQueue = new ReferenceQueue(); //reference will be stored in this queue for cleanup DigitalCounter digit = new DigitalCounter(); PhantomReference<DigitalCounter> phantom = new PhantomReference<DigitalCounter>(digit, refQueue);
Reference of instance will be appended to ReferenceQueue and you can use it to perform any clean-up by polling ReferenceQueue. An Object's life-cycle is nicely summed up by this diagram.
That's all on Difference between WeakReference and SoftReference in Java. We also learned basics of reference classes e.g. Weak, soft and phantom reference in Java and WeakHashMap and ReferenceQueue. Careful use of reference can assist Garbage Collection and result in better memory management in Java.
相关推荐
SoftReference、WeakReference和PhantomRefrence分析和比较
StrongReference,SoftReference, WeakReference的使用实例,请参照博客:http://blog.csdn.net/To_be_Designer/article/details/72673421
ava有四种引用类型,strongreference,softreference,weakreference,phantomreference。本篇文档主要的就是进阶的介绍和了解这四种引用类型的异同点,助于你对java的更好的学习理解
周期无法控制可以采用SoftReference,WeakReference,PhantomReference这三种对象来执行(看了Ibatis的缓存机制才发现JDK居然还提供了PhantomReference这玩意儿,得恶补基础啊),这三种都是弱引用,区别在于强度...
3.1 强引 3.2 软引 3.3 弱引 3. 4 假象引
该Demo主要原理: 加载图片时先查看缓存中时候存在该图片,如果存在则返回该图片,否则先加载载一个...并且处理的多个细节,包括使用WeakReference、SoftReference防止内存溢出、解决使用Handler时context泄露问题 登
1.强引用1.强引用 2.软引用(SoftReference) 3.弱引用(WeakReference) 4.虚引用(PhantomReference) 等等;
├─Google Guava 第29讲-SoftReference,WeakReference,PhantomReference精讲.wmv ├─Google Guava 第30讲-SoftReference加LRU算法实现InMemoryCache.wmv ├─Google Guava 第31讲-Guava之CacheLoader,...
这个项目为万能的(有时是可怕的)弱引用实现了一个kotlin包装器,以便您可以更友好地使用它们。
AsyncTask_WeakReference
我们平常用的都是对象的强引用,如果有强引用存在,GC是不会回收对象的。我们能不能同时保持对对象的引用,而又可以让GC需要的时候回收这个对象呢?... WeakReference wref = new WeakReference( obj ); obj
他们分别是强引用(StrongReference),软引用(SoftReference),弱引用(WeakReference)以及PhantomReference(虚引用),他们被 GC回收的可能性从小到大排列。 强引用(StrongReference) 只要强引用存在,垃圾回收器将...
主要介绍了Java弱引用(WeakReference)的理解与使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
前述:除了强引用外,其他引用不是我们所常见的 new出来的对象,而是需要借用3个类SoftReference软引用,WeakReference弱引用,PhantomReference虚引用 1.强引用 概述:即发生OOM(Out Of Memory)内存空间满了也...
创建用于WPF MVVM绑定的Singleton,并对绑定的属性使用弱引用的概念。
这是对 java.lang.ref.WeakReference 实现的修改,它将通过 JMX MBean 跟踪和报告它发现的内容。如何使用: 在您的应用程序中启用 JMX。 然后使用指向此实现的引导类路径启动 Java 应用程序。 例如: $ java -...
强引用(StrongReference) 23 软引用(SoftReference) 23 弱引用(WeakReference) 23 虚引用(PhantomReference) 24 【基础】final, finally, finalize的区别 24 【基础】Java 中定义常量的几种方法 25 【基础】...
弱参考测试 代码测试 ...或在命令行上创建一个新的存储库 touch README.md git init git add README.md git commit -m "first commit" git remote add origin git push -u origin master ......git remote add origin ...