从JDK1.2开始,就提供了四种类型的引用:强引用、软引用、弱引用和虚引用。Java中提供这四种引用类型主要有两个目的:第一是可以让程序员通过代码的方式决定某些对象的生命周期;第二是有利于JVM进行垃圾回收。
1.强引用(StrongReference)
强引用就是指在程序代码之中普遍存在的,比如下面这段代码中的object和str都是强引用:
Object object = new Object(); String str = "hello";
只要某个对象有强引用与之关联,JVM必定不会回收这个对象,即使在内存不足的情况下,JVM宁愿抛出OutOfMemory错误也不会回收这种对象。
package org.fool.reference; public class StrongReferenceTest { public static void main(String[] args) { new StrongReferenceTest().test(); } public void test() { /** * 强引用就是指在程序代码之中普遍存在的,比如下面这段代码中的object和objects都是强引用 * 只要某个对象有强引用与之关联,JVM必定不会回收这个对象,即使在内存不足的情况下, * JVM宁愿抛出OutOfMemory错误也不会回收这种对象 */ Object object = new Object(); Object[] objects = new Object[100]; /** * 当运行至Object[] objArr = new Object[100];这句时,如果内存不足,JVM会抛出OOM错误也不会回收object指向的对象。 * 不过要注意的是,当test运行完之后,object和objects都已经不存在了,所以它们指向的对象都会被JVM回收。 * 如果想中断强引用和某个对象之间的关联,可以显示地将引用赋值为null,这样一来的话,JVM在合适的时间就会回收该对象。 */ } }
2.软引用(SoftReference)
软引用是用来描述一些有用但并不是必需的对象,在Java中用java.lang.ref.SoftReference类来表示。对于软引用关联着的对象,只有在内存不足的时候JVM才会回收该对象。
package org.fool.reference; import java.lang.ref.SoftReference; public class SoftRefereneceTest { public static void main(String[] args) { /** * 软引用是用来描述一些有用但并不是必需的对象,在Java中用java.lang.ref.SoftReference类来表示。 * 对于软引用关联着的对象,只有在内存不足的时候JVM才会回收该对象。因此,这一点可以很好地用来解决OOM的问题, * 并且这个特性很适合用来实现缓存:比如网页缓存、图片缓存等。 * 软引用可以和一个引用队列(ReferenceQueue)联合使用,如果软引用所引用的对象被JVM回收,这个软引用就会被加入到与之关联的引用队列中。 */ SoftReference<String> sr = new SoftReference<>(new String("hello")); System.out.println(sr.get()); // hello System.gc(); System.out.println(sr.get()); // hello } }
3.弱引用(WeakReference)
弱引用也是用来描述非必需对象的,当JVM进行垃圾回收时,无论内存是否充足,都会回收被弱引用关联的对象。在java中,用java.lang.ref.WeakReference类来表示。
package org.fool.reference; import java.lang.ref.WeakReference; public class WeakReferenceTest { public static void main(String[] args) { /** * 弱引用也是用来描述非必需对象的,当JVM进行垃圾回收时,无论内存是否充足,都会回收被弱引用关联的对象。 * 在java中,用java.lang.ref.WeakReference类来表示。 */ WeakReference<String> wr = new WeakReference<>(new String("hello")); System.out.println(wr.get()); // hello System.gc(); System.out.println(wr.get()); // null /** * 第二个输出结果是null,这说明只要JVM进行垃圾回收,被弱引用关联的对象必定会被回收掉。 * 不过要注意的是,这里所说的被弱引用关联的对象是指只有弱引用与之关联, * 如果存在强引用同时与之关联,则进行垃圾回收时也不会回收该对象(软引用也是如此)。 * 弱引用可以和一个引用队列(ReferenceQueue)联合使用, * 如果弱引用所引用的对象被JVM回收,这个软引用就会被加入到与之关联的引用队列中。 */ } }
4.虚引用(PhantomReference)
虚引用和前面的软引用、弱引用不同,它并不影响对象的生命周期。在java中用java.lang.ref.PhantomReference类表示。如果一个对象与虚引用关联,则跟没有引用与之关联一样,在任何时候都可能被垃圾回收器回收。
package org.fool.reference; import java.lang.ref.PhantomReference; import java.lang.ref.ReferenceQueue; public class PhantomReferenceTest { public static void main(String[] args) { /** * 虚引用和前面的软引用、弱引用不同,它并不影响对象的生命周期。在java中用java.lang.ref.PhantomReference类表示。 * 如果一个对象与虚引用关联,则跟没有引用与之关联一样,在任何时候都可能被垃圾回收器回收。 * 要注意的是,虚引用必须和引用队列关联使用,当垃圾回收器准备回收一个对象时, * 如果发现它还有虚引用,就会把这个虚引用加入到与之 关联的引用队列中。 * 程序可以通过判断引用队列中是否已经加入了虚引用,来了解被引用的对象是否将要被垃圾回收。 * 如果程序发现某个虚引用已经被加入到引用队列,那么就可以在所引用的对象的内存被回收之前采取必要的行动。 */ ReferenceQueue<String> queue = new ReferenceQueue<>(); PhantomReference<String> pr = new PhantomReference<>(new String("hello"), queue); System.out.println(pr.get()); // null System.gc(); System.out.println(pr.get()); // null } }
对于强引用,我们平时在编写代码时经常会用到。而对于其他三种类型的引用,使用得最多的就是软引用和弱引用,这两种既有相似之处又有区别。它们都是用来描述非必需对象的,但是被软引用关联的对象只有在内存不足时才会被回收,而被弱引用关联的对象在JVM进行垃圾回收时总会被回收。
在SoftReference类中,有三个方法,两个构造方法和一个get方法(WeakReference类似):
package java.lang.ref; /** * Soft reference objects, which are cleared at the discretion of the garbage * collector in response to memory demand. Soft references are most often used * to implement memory-sensitive caches. * * <p> Suppose that the garbage collector determines at a certain point in time * that an object is <a href="package-summary.html#reachability">softly * reachable</a>. At that time it may choose to clear atomically all soft * references to that object and all soft references to any other * softly-reachable objects from which that object is reachable through a chain * of strong references. At the same time or at some later time it will * enqueue those newly-cleared soft references that are registered with * reference queues. * * <p> All soft references to softly-reachable objects are guaranteed to have * been cleared before the virtual machine throws an * <code>OutOfMemoryError</code>. Otherwise no constraints are placed upon the * time at which a soft reference will be cleared or the order in which a set * of such references to different objects will be cleared. Virtual machine * implementations are, however, encouraged to bias against clearing * recently-created or recently-used soft references. * * <p> Direct instances of this class may be used to implement simple caches; * this class or derived subclasses may also be used in larger data structures * to implement more sophisticated caches. As long as the referent of a soft * reference is strongly reachable, that is, is actually in use, the soft * reference will not be cleared. Thus a sophisticated cache can, for example, * prevent its most recently used entries from being discarded by keeping * strong referents to those entries, leaving the remaining entries to be * discarded at the discretion of the garbage collector. * * @author Mark Reinhold * @since 1.2 */ public class SoftReference<T> extends Reference<T> { /** * Timestamp clock, updated by the garbage collector */ static private long clock; /** * Timestamp updated by each invocation of the get method. The VM may use * this field when selecting soft references to be cleared, but it is not * required to do so. */ private long timestamp; /** * Creates a new soft reference that refers to the given object. The new * reference is not registered with any queue. * * @param referent object the new soft reference will refer to */ public SoftReference(T referent) { super(referent); this.timestamp = clock; } /** * Creates a new soft reference that refers to the given object and is * registered with the given queue. * * @param referent object the new soft reference will refer to * @param q the queue with which the reference is to be registered, * or <tt>null</tt> if registration is not required * */ public SoftReference(T referent, ReferenceQueue<? super T> q) { super(referent, q); this.timestamp = clock; } /** * Returns this reference object's referent. If this reference object has * been cleared, either by the program or by the garbage collector, then * this method returns <code>null</code>. * * @return The object to which this reference refers, or * <code>null</code> if this reference object has been cleared */ public T get() { T o = super.get(); if (o != null && this.timestamp != clock) this.timestamp = clock; return o; } }
get方法用来获取与软引用关联的对象的引用,如果该对象被回收了,则返回null。
在使用软引用和弱引用的时候,我们可以显示地通过System.gc()来通知JVM进行垃圾回收,但是要注意的是,虽然发出了通知,JVM不一定会立刻执行,也就是说这句是无法确保此时JVM一定会进行垃圾回收的。
参考资料转自:
http://www.cnblogs.com/dolphin0520/p/3784171.html
相关推荐
前言从JavaSE2开始,就提供了四种类型的引用:强引用、软引用、弱引用和虚引用。Java中提供这四种引用类型主要有两个目的:第一是可以让程序员通过代码的方式决
Java中弱引用软引用虚引用及强引用的区别Java开发Java经验技巧共3页.pdf.zip
Java 7之基础 - 强引用、弱引用、软引用、虚引用1
referenceInJava:Java强引用,软引用,弱引用以及虚引用测试项目
笔者自己的通俗总结,5分钟搞清楚java中强软弱虚引用的区别^_^
很早Java API就添加了弱引用(WeakReference)和软引用(SoftReference),但并不是所有的程序员都熟悉这两个概念
java有四种引用类型:强引用、软引用、弱引用、虚引用 四大引用设计作用 因为java的内存分配和内存回收,都是由JVM去负责,一个对象是否可以被回收,主要看是否有引用指向此对象,即可达性分析 设计目的: 可以让...
弱引用强引用支持区别
3.2 如果使用软引用SoftReference的特点是它的一个实例保存对一个Java对象的软引用,该软引用的存在不妨碍垃圾收集线程对该Java对象的回收 3.
在JDK1.2以前的版本中,当一个对象不被任何变量引用,那么程序就无法再使用这个对象。也就是说,只有对象处于可触及状态,程序才能使用它。这 就像在日常生活中,从商店购买了某样物品后,如果有用,就一直保留它,...
Bitmap图片的三级缓存DEMO 三层缓存 强引用 软引用DEMO
强引用可以直接访问目标对象强引用所指向的对象在任何时候都不会被系统回收,虚拟机宁愿抛出OOM异常,也不会回收强引用所指向的对象强引用可能导致内存泄漏软引用一个对
想必很多朋友对OOM(OutOfMemory)这个错误不会陌生,而当遇到这种... 从Java SE2开始,就提供了四种类型的引用:强引用、软引用、弱引用和虚引用。Java中提供这四种引用类型主要有两个目的:第一是可以让程序员通过
(比如新创建一个对象,那么创建它的线程对它就是强可达)\2. 软可达: 只能通过软引用才能访问到对象状态\3. 弱可达: 只能通过弱引用访问时的状态, 十分临近
实现了图片的三级缓存. 欢迎留言讨论
前述:除了强引用外,其他引用不是我们所常见的 new出来的对象,而是需要借用3个类SoftReference软引用,WeakReference弱引用,PhantomReference虚引用 1.强引用 概述:即发生OOM(Out Of Memory)内存空间满了也...
主要介绍了Java中强引用,软引用,弱引用概念解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
文章目录内存回收引用计数法可达性分析浅谈引用强引用软引用弱引用虚引用方法区GC 算法标记-清除算法(Mark-Sweep)复制算法(Copying)标记-整理算法(Mark-Compact)GC算法综合用年轻代老年代永久代枚举根节点安全...
在 Java 中,引用类型分为强引用、软引用、弱引用和虚引用四种。强引用是我们最常用的引用类型,而软引用、弱引用和虚引用则是 Java 为我们提供的三种特殊的引用类型,它们可以和 GC 做交互,以满足不同的应用场景。...
首先我表示很悲剧,在看《程序员的自我修养–链接、装载与库》之前我竟不知道C有强符号、弱符号、强引用和弱引用。在看到3.5.5节弱符号和强符号时,我感觉有些困惑,所以写下此篇,希望能和同样感觉的朋友交流也希望...