从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