JDK1.2 之前,Java 中引用的定义很传统:如果 reference 类型的数据存储的数值代表的是另一块内存的起始地址,就称这块内存代表一个引用。
JDK1.2 以后,Java 对引用的概念进行了扩充,将引用分为强引用、软引用、弱引用、虚引用四种(引用强度逐渐减弱)
1.强引用
以前我们使用的大部分引用实际上都是强引用,这是使用最普遍的引用。如果一个对象具有强引用,那就类似于必不可少的生活用品,垃圾回收器绝不会回收它。当内存空间不足,Java 虚拟机宁愿抛出 OutOfMemoryError 错误,使程序异常终止,也不会靠随意回收具有强引用的对象来解决内存不足问题。
2.软引用(SoftReference)
如果一个对象只具有软引用,那就类似于可有可无的生活用品。如果内存空间足够,垃圾回收器就不会回收它,如果内存空间不足了,就会回收这些对象的内存。只要垃圾回收器没有回收它,该对象就可以被程序使用。软引用可用来实现内存敏感的高速缓存。
软引用可以和一个引用队列(ReferenceQueue)联合使用,如果软引用所引用的对象被垃圾回收,JAVA 虚拟机就会把这个软引用加入到与之关联的引用队列中。
3.弱引用(WeakReference)
如果一个对象只具有弱引用,那就类似于可有可无的生活用品。弱引用与软引用的区别在于:只具有弱引用的对象拥有更短暂的生命周期。在垃圾回收器线程扫描它所管辖的内存区域的过程中,一旦发现了只具有弱引用的对象,不管当前内存空间足够与否,都会回收它的内存。不过,由于垃圾回收器是一个优先级很低的线程, 因此不一定会很快发现那些只具有弱引用的对象。
弱引用可以和一个引用队列(ReferenceQueue)联合使用,如果弱引用所引用的对象被垃圾回收,Java 虚拟机就会把这个弱引用加入到与之关联的引用队列中。
4.虚引用(PhantomReference)
“虚引用”顾名思义,就是形同虚设,与其他几种引用都不同,虚引用并不会决定对象的生命周期。如果一个对象仅持有虚引用,那么它就和没有任何引用一样,在任何时候都可能被垃圾回收。
虚引用主要用来跟踪对象被垃圾回收的活动。
虚引用与软引用和弱引用的一个区别在于: 虚引用必须和引用队列(ReferenceQueue)联合使用。当垃圾回收器准备回收一个对象时,如果发现它还有虚引用,就会在回收对象的内存之前,把这个虚引用加入到与之关联的引用队列中。程序可以通过判断引用队列中是否已经加入了虚引用,来了解被引用的对象是否将要被垃圾回收。程序如果发现某个虚引用已经被加入到引用队列,那么就可以在所引用的对象的内存被回收之前采取必要的行动。
特别注意,在程序设计中一般很少使用弱引用与虚引用,使用软引用的情况较多,这是因为软引用可以加速 JVM 对垃圾内存的回收速度,可以维护系统的运行安全,防止内存溢出(OutOfMemory)等问题的产生。
一个防止内存溢出的缓存Map:
import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; import java.util.AbstractMap; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Set; public class SoftHashMap extends AbstractMap<String, Object> { /** The internal HashMap that will hold the SoftReference. */ /** 使用一个HashMap 保存弱引用的值 */ private final Map<String, Object> hash = new HashMap<String, Object>(); /** The number of "hard" references to hold internally. */ /** 热点缓存数量 */ private final int HARD_SIZE; /** The FIFO list of hard references, order of last access. */ /** 保存热点缓存的强应用 */ private final LinkedList<Object> hardCache = new LinkedList<Object>(); /** Reference queue for cleared SoftReference objects. */ /** 软引用被回收后的队列 */ private final ReferenceQueue<Object> queue = new ReferenceQueue<Object>(); public SoftHashMap() { this(100); } public SoftHashMap(int hardSize) { HARD_SIZE = hardSize; } public Object get(String key) { Object result = null; // We get the SoftReference represented by that key SoftReference<Object> soft_ref = (SoftReference<Object>) hash.get(key); if (soft_ref != null) { // From the SoftReference we get the value, which can be // null if it was not in the map, or it was removed in // the processQueue() method defined below result = soft_ref.get(); if (result == null) { // If the value has been garbage collected, remove the // entry from the HashMap. hash.remove(key); } else { // We now add this object to the beginning of the hard // reference queue. One reference can occur more than // once, because lookups of the FIFO queue are slow, so // we don't want to search through it each time to remove // duplicates. hardCache.addFirst(result); if (hardCache.size() > HARD_SIZE) { // Remove the last entry if list longer than HARD_SIZE hardCache.removeLast(); } } } return result; } /** * We define our own subclass of SoftReference which contains not only the * value but also the key to make it easier to find the entry in the HashMap * after it's been garbage collected. */ private static class SoftValue extends SoftReference { private final Object key; // always make data member final /** * Did you know that an outer class can access private data members and * methods of an inner class? I didn't know that! I thought it was only * the inner class who could access the outer class's private * information. An outer class can also access private members of an * inner class inside its inner class. */ private SoftValue(Object k, Object key, ReferenceQueue q) { super(k, q); this.key = key; } } /** * Here we go through the ReferenceQueue and remove garbage collected * SoftValue objects from the HashMap by looking them up using the * SoftValue.key data member. */ private void processQueue() { SoftValue sv; while ((sv = (SoftValue) queue.poll()) != null) { hash.remove(sv.key); // we can access private data! } } /** * Here we put the key, value pair into the HashMap using a SoftValue * object. */ public Object put(String key, Object value) { processQueue(); // throw out garbage collected values first return hash.put(key, new SoftValue(value, key, queue)); } public Object remove(Object key) { processQueue(); // throw out garbage collected values first return hash.remove(key); } public void clear() { hardCache.clear(); processQueue(); // throw out garbage collected values hash.clear(); } public int size() { processQueue(); // throw out garbage collected values first return hash.size(); } public Set entrySet() { // no, no, you may NOT do that!!! GRRR throw new UnsupportedOperationException(); } }