`
jimode2013
  • 浏览: 39366 次
社区版块
存档分类
最新评论

Difference between WeakReference vs SoftReference vs PhantomReference vs Strong

 
阅读更多

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 :

  1. Strong reference
  2. Weak Reference
  3. Soft Reference
  4. 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 nullCounter 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 WeakReferenceSoftReferencePhantomReference and WeakHashMap there is one more class called ReferenceQueue which is worth knowing. You can supply a ReferenceQueue instance while creating any WeakReferenceSoftReference 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.

 

 

  • 大小: 31.5 KB
分享到:
评论

相关推荐

    SoftReference、WeakReference和PhantomRefrence分析和比较

    SoftReference、WeakReference和PhantomReference分析和比较 在 Java 中,引用类型分为强引用、软引用、弱引用和虚引用四种。强引用是我们最常用的引用类型,而软引用、弱引用和虚引用则是 Java 为我们提供的三种...

    StrongReference,SoftReference, WeakReference的使用实例

    StrongReference,SoftReference, WeakReference的使用实例,请参照博客:http://blog.csdn.net/To_be_Designer/article/details/72673421

    Java引用总结--StrongReference、SoftReference、WeakReference、PhantomRef

    Java从1.2版本开始引入了四种引用,分别是强引用(StrongReference)、软引用(SoftReference)、弱引用(WeakReference)和虚引用(PhantomReference)。这四种引用的级别由高到低依次为:强引用 &gt; 软引用 &gt; 弱引用...

    redis基础.rar

    周期无法控制可以采用SoftReference,WeakReference,PhantomReference这三种对象来执行(看了Ibatis的缓存机制才发现JDK居然还提供了PhantomReference这玩意儿,得恶补基础啊),这三种都是弱引用,区别在于强度...

    00M原因以及分析处理

    5. 使用WeakReference和SoftReference: WeakReference和SoftReference可以帮助开发者更好地管理应用程序中的对象生命周期。 OOM错误的常见解决方法 1. 使用System.gc():System.gc()可以强制垃圾回收器回收垃圾...

    深入探讨 java-lang-ref 包.docx

    总结,java.lang.ref 包中的四种引用类型——StrongReference、SoftReference、WeakReference 和 PhantomReference,提供了不同的内存管理策略,适应不同的场景需求。强引用是最常用的引用类型,但在处理大对象或...

    Java中内存泄露及垃圾回收机制参照.pdf

    4. 使用WeakReference和SoftReference,WeakReference和SoftReference可以帮助避免内存泄漏。 Java的垃圾回收机制可以自动回收内存中的垃圾,避免内存泄漏,但是程序员需要注意避免内存泄漏的几点,以确保程序的...

    深入探讨 java.lang.ref 包1

    本文将深入探讨这个包中的四种主要引用类型:StrongReference、SoftReference、WeakReference 和 PhantomReference,以及它们的特性、用法和作用。 首先,强引用(StrongReference)是我们在日常编程中最常见的引用...

    JVM 77 道面试题及答案.docx

    4. WeakReference 与 SoftReference: WeakReference 和 SoftReference 都可以用于提高 GC 和内存的效率,但是 WeakReference 一旦失去最后一个强引用,就会被 GC 回收,而软引用虽然不能阻止被回收,但是可以延迟到...

    Android 图片下载以及内存处理防止OOM内存溢出 源码

    - 使用WeakReference和SoftReference:当需要引用一些可能引发内存泄漏的对象时,可以使用WeakReference或SoftReference,使得对象能在不被使用的状态下被垃圾回收。 4. **源码分析**: - `JavaApk源码说明.txt`...

    博客 工作中遇到的Android内存优化问题demo

    对于那些可能引起内存泄漏的引用,可以考虑使用WeakReference或SoftReference。WeakReference在对象无其他强引用时会立即被回收,而SoftReference在系统内存紧张时才会被回收。 8. 观察者模式与内存泄漏: 注册...

    安卓Android源码——图片下载以及内存处理防OOM.zip

    3. **WeakReference与SoftReference**:使用WeakReference或SoftReference持有Bitmap或其他大型对象,当内存不足时,这些引用的对象会优先被回收。 4. **Memory Analyzer Tool (MAT)**:Android提供的内存分析工具...

    Android异步加载图片Demo

    该Demo主要原理: 加载图片时先查看缓存中时候存在该图片,如果存在则返回该图片,否则先加载载一个...并且处理的多个细节,包括使用WeakReference、SoftReference防止内存溢出、解决使用Handler时context泄露问题 登

    Android Volley,AsyncTask,FinalHttp 请求对比内存泄漏

    1. **使用WeakReference或SoftReference**:在Volley或其他库中,可以考虑使用WeakReference或SoftReference来持有Activity引用,这样当Activity销毁时,引用会被自动清除,避免内存泄漏。 2. **正确管理生命周期**...

    Android学习资料之内存优化.zip

    - 使用WeakReference和SoftReference:避免强引用导致的对象无法回收,可以使用WeakReference或SoftReference弱化对象引用。 - 避免过度绘制:减少不必要的视图层次,优化布局,防止GPU过度绘制。 - 资源复用:例如...

    基于Android防止内存溢出浅析

    WeakReference和SoftReference可以创建对对象的弱引用和软引用,它们不会阻止垃圾回收器清理对象。在需要临时存储对象但又不希望影响其生命周期的情况下,可以考虑使用这两种引用类型。 **避免无限制的递归** 无限...

    Android-memroy.zip_android_android 优化

    使用WeakReference和SoftReference可以帮助开发者实现弱引用和软引用,让对象在内存不足时能被及时回收,防止内存泄漏。 4. **Bitmap优化** Bitmap是Android中消耗内存的主要因素之一。通过合理设置Bitmap的配置...

Global site tag (gtag.js) - Google Analytics