Java-Collections Framework学习与总结-WeakHashMap

来源:互联网 发布:安卓手机照片导入mac 编辑:程序博客网 时间:2024/05/04 11:07
     总结这个类之前,首先看一下Java引用的相关知识。Java的引用分为四种:强引用、软引用、弱引用和虚引用。

        强引用:就是常见的代码中的引用,如Object o = new Object();存在强引用的对象不会被垃圾收集器回收。所以我们会在一些代码中看到显示切断强引用,以便回收相关对象的情况。
Java代码  收藏代码
  1. public void clear() {  
  2.     modCount++;  
  3.   
  4.     // Let gc do its work  
  5.     for (int i = 0; i < size; i++)  
  6.         elementData[i] = null;  
  7.   
  8.     size = 0;  
  9. }  


        软引用:比强引用弱一些,表示对一些有用但非必须对象的引用。这些对象会在将要发生内存溢出异常之前被回收。在Java中用java.lang.ref.SoftReference来表示软引用。看一个例子,先设置下JVM参数,将堆大小设为10m,老年代新生代各5m,打印出GC日志。
JVM参数
Java代码  收藏代码
  1. -Xms10m -Xmx10m -Xmn5m -XX:+PrintGCDetails  

Java代码  收藏代码
  1. public static void main(String[] args) {  
  2.     //构造一个3M的对象  
  3.     Object _3m_1 = new byte[1024 * 1024 * 3];  
  4.     //创建软引用  
  5.     SoftReference<Object> reference = new SoftReference<Object>(_3m_1);  
  6.     //切断强引用  
  7.     _3m_1 = null;  
  8.     //再构造一个3M的对象  
  9.     Object _3m_2 = new byte[1024 * 1024 * 3];  
  10.     //触发Full GC  
  11.     System.gc();  
  12.     System.out.println("软引用关联对象:"+reference.get());  
  13. }  

        输出结果:
Java代码  收藏代码
  1. [GC [DefNew: 3325K->152K(4608K), 0.0023022 secs] 3325K->3224K(9728K), 0.0023380 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]   
  2. [Full GC (System) [Tenured: 3072K->3072K(5120K), 0.0057404 secs] 6378K->6296K(9728K), [Perm : 380K->380K(12288K)], 0.0057837 secs] [Times: user=0.02 sys=0.00, real=0.02 secs]   
  3. 软引用关联对象:[B@14318bb  
  4. Heap  
  5.  def new generation   total 4608K, used 3350K [0x31fe00000x324e00000x324e0000)  
  6.   eden space 4096K,  81% used [0x31fe00000x323258800x323e0000)  
  7.   from space 512K,   0% used [0x324600000x324600000x324e0000)  
  8.   to   space 512K,   0% used [0x323e00000x323e00000x32460000)  
  9.  tenured generation   total 5120K, used 3072K [0x324e00000x329e00000x329e0000)  
  10.    the space 5120K,  60% used [0x324e00000x327e00100x327e02000x329e0000)  
  11.  compacting perm gen  total 12288K, used 380K [0x329e00000x335e00000x369e0000)  

        基本过程是这样,程序先创建了一个3M的对象_3m_1,这个对象被分配到新生代里面,然后创了一个软引用关联到_3m_1,然后切断_3m_1的强引用。接下来又创建了一个3M的对象_3m_2,_3m_2要试图分配到新生代,这时发现新生代剩余空间不足(一共4608K,已经有一个3M的对象在里面)。接下来触发了一次新生代的垃圾收集动作(Minor GC),但这次收集没有回收掉_3m_1。然后_3m_1晋升到老年代,_3m_2被分配到新生代。接下来程序显示触发了一次Full GC,但这次Full GC似乎没起什么作用,_3m_1和_3m_2都安然无恙。
        那么修改一下程序,再跑一次看看:
Java代码  收藏代码
  1. public static void main(String[] args) {  
  2.     //构造一个3M的对象  
  3.     Object _3m_1 = new byte[1024 * 1024 * 3];  
  4.     //创建软引用  
  5.     SoftReference<Object> reference = new SoftReference<Object>(_3m_1);  
  6.     //切断强引用  
  7.     _3m_1 = null;  
  8.     //再构造一个3M的对象  
  9.     Object _3m_2 = new byte[1024 * 1024 * 3];  
  10.     //又构造一个3M的对象  
  11.     Object _3m_3 = new byte[1024 * 1024 * 3];  
  12.     System.out.println("软引用关联对象:"+reference.get());  
  13. }  

        输出结果:
Java代码  收藏代码
  1. [GC [DefNew: 3325K->152K(4608K), 0.0021553 secs] 3325K->3224K(9728K), 0.0021908 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]   
  2. [GC [DefNew: 3224K->3224K(4608K), 0.0000288 secs][Tenured: 3072K->3072K(5120K), 0.0060759 secs] 6296K->6296K(9728K), [Perm : 380K->380K(12288K)], 0.0061594 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]   
  3. [Full GC [Tenured: 3072K->3210K(5120K), 0.0049693 secs] 6296K->3210K(9728K), [Perm : 380K->375K(12288K)], 0.0050152 secs] [Times: user=0.01 sys=0.00, real=0.02 secs]   
  4. 软引用关联对象:null  
  5. Heap  
  6.  def new generation   total 4608K, used 3280K [0x31fe00000x324e00000x324e0000)  
  7.   eden space 4096K,  80% used [0x31fe00000x323140500x323e0000)  
  8.   from space 512K,   0% used [0x324600000x324600000x324e0000)  
  9.   to   space 512K,   0% used [0x323e00000x323e00000x32460000)  
  10.  tenured generation   total 5120K, used 3210K [0x324e00000x329e00000x329e0000)  
  11.    the space 5120K,  62% used [0x324e00000x32802b280x32802c000x329e0000)  

        前面的过程和上面类似,区别在创建第三个3M对象_3m_3时,首先触发了一次Minor GC,没回收什么东西,但是要把新生代里的_3m_2放到老年代,这样才能腾出地方给_3m_3。但是老年代已经有_3m_1了,剩余的空间不足以放下_3m_2,这时系统触发了Full GC(不用我们触发system Full GC了)。从日志上看似乎回收掉了3M的空间。说明在内存溢出之前,软引用关联的对象被回收了。这便是软引用的特性,如果这里是一个强引用的话,那么便会出现OOM了。

        弱引用:比软引用还弱一些,所以关联的对象在下一次垃圾收集的时候就会被回收掉。继续看例子,JVM参数同上。
Java代码  收藏代码
  1. public static void main(String[] args) {  
  2.     //构造一个3M的对象  
  3.     Object _3m_1 = new byte[1024 * 1024 * 3];  
  4.     //创建软引用  
  5.     WeakReference<Object> reference = new WeakReference<Object>(_3m_1);  
  6.     //切断强引用  
  7.     _3m_1 = null;  
  8.     //触发Full GC  
  9.     System.gc();  
  10.     System.out.println("软引用关联对象:"+reference.get());  
  11. }  

        输出结果:
Java代码  收藏代码
  1. [Full GC (System) [Tenured: 0K->152K(5120K), 0.0086388 secs] 3325K->152K(9728K), [Perm : 380K->380K(12288K)], 0.0086922 secs] [Times: user=0.01 sys=0.00, real=0.01 secs]   
  2. 软引用关联对象:null  
  3. Heap  
  4.  def new generation   total 4608K, used 208K [0x31fe00000x324e00000x324e0000)  
  5.   eden space 4096K,   5% used [0x31fe00000x320140400x323e0000)  
  6.   from space 512K,   0% used [0x323e00000x323e00000x32460000)  
  7.   to   space 512K,   0% used [0x324600000x324600000x324e0000)  
  8.  tenured generation   total 5120K, used 152K [0x324e00000x329e00000x329e0000)  
  9.    the space 5120K,   2% used [0x324e00000x325060880x325062000x329e0000)  


        虚引用:虚引用一般用来代替finalize方法来做一些引用对象被回收前的清理动作(由于finalize的不确定性,不建议使用)。虚引用必须配合一个ReferenceQueue一起使用,在GC决定要回收其引用对象时(引用对象没有任何强引用关联),虚引用会入栈,程序中可以在这个时机做一些清理工作。虚引用的get方法返回null:
Java代码  收藏代码
  1. public class PhantomReference<T> extends Reference<T> {  
  2.   
  3.     /** 
  4.      * Returns this reference object's referent.  Because the referent of a 
  5.      * phantom reference is always inaccessible, this method always returns 
  6.      * <code>null</code>. 
  7.      * 
  8.      * @return  <code>null</code> 
  9.      */  
  10.     public T get() {  
  11.     return null;  
  12.     }  

        这样保证了虚引用的关联对象永远不可能通过get方法再次获得强引用。但虚引用的关联对象要一直等到虚引用本身不可达或者被回收时才能够被回收,这点不同于软引用和弱引用。
  
        最后说一下java.lang.ref.ReferenceQueue。ReferenceQueue是一个引用队列,构造一个软引用、弱引用或者虚引用可以传入一个ReferenceQueue,表示这个引用注册到传入的引用队列上,简单的说,当GC决定回收引用关联对象时,会将这个引用放到引用队列里。

        大概了解了Java引用的相关内容,现在可以看下java.util.WeakHashMap的源码了。
        整体看下来,其实和HashMap差不多,所以只看一下差异的地方。
Java代码  收藏代码
  1. /** 
  2.  * Reference queue for cleared WeakEntries 
  3.  */  
  4. private final ReferenceQueue<K> queue = new ReferenceQueue<K>();  

        WeakHashMap中多了一个引用队列的变量,大概能猜到是干什么的了吧。
      
        看下WeakHashMap中的Entry:
Java代码  收藏代码
  1. /** 
  2.  * The entries in this hash table extend WeakReference, using its main ref 
  3.  * field as the key. 
  4.  */  
  5. private static class Entry<K,V> extends WeakReference<K> implements Map.Entry<K,V> {  
  6.     private V value;  
  7.     private final int hash;  
  8.     private Entry<K,V> next;  
  9.   
  10.     /** 
  11.      * Creates new entry. 
  12.      */  
  13.     Entry(K key, V value,  
  14.    ReferenceQueue<K> queue,  
  15.           int hash, Entry<K,V> next) {  
  16.         super(key, queue);  
  17.         this.value = value;  
  18.         this.hash  = hash;  
  19.         this.next  = next;  
  20.     }  
  21.   
  22.     public K getKey() {  
  23.         return WeakHashMap.<K>unmaskNull(get());  
  24.     }  
  25.   
  26.     public V getValue() {  
  27.         return value;  
  28.     }  
  29.   
  30.     public V setValue(V newValue) {  
  31.  V oldValue = value;  
  32.         value = newValue;  
  33.         return oldValue;  
  34.     }  
  35.   
  36.     public boolean equals(Object o) {  
  37.         if (!(o instanceof Map.Entry))  
  38.             return false;  
  39.         Map.Entry e = (Map.Entry)o;  
  40.         Object k1 = getKey();  
  41.         Object k2 = e.getKey();  
  42.         if (k1 == k2 || (k1 != null && k1.equals(k2))) {  
  43.             Object v1 = getValue();  
  44.             Object v2 = e.getValue();  
  45.             if (v1 == v2 || (v1 != null && v1.equals(v2)))  
  46.                 return true;  
  47.         }  
  48.         return false;  
  49.     }  
  50.   
  51.     public int hashCode() {  
  52.         Object k = getKey();  
  53.         Object v = getValue();  
  54.         return  ((k==null ? 0 : k.hashCode()) ^  
  55.                  (v==null ? 0 : v.hashCode()));  
  56.     }  
  57.   
  58.     public String toString() {  
  59.         return getKey() + "=" + getValue();  
  60.     }  
  61. }  

        java.util.WeakHashMap.Entry扩展自java.lang.ref.WeakReference,将Key(Map中的键)作为虚引用的关联对象。
        由于WeakHashMap本身允许键值为null,所以这里不同于HashMap,需要利用一些转化函数。
Java代码  收藏代码
  1. /** 
  2.  * Value representing null keys inside tables. 
  3.  */  
  4. private static final Object NULL_KEY = new Object();  
  5.   
  6. /** 
  7.  * Use NULL_KEY for key if it is null. 
  8.  */  
  9. private static Object maskNull(Object key) {  
  10.     return (key == null ? NULL_KEY : key);  
  11. }  
  12.   
  13. /** 
  14.  * Returns internal representation of null key back to caller as null. 
  15.  */  
  16. private static <K> K unmaskNull(Object key) {  
  17.     return (K) (key == NULL_KEY ? null : key);  
  18. }  

        由于虚引用的性质,当WeakHashMap中的某个Key已经没有外部的强引用,那么在接下来发生的垃圾收集动作里,它将会被回收。这里要注意一下,回收的仅仅是Key,但是Entry还在呢(也可以说是虚引用本身)。
        所以在一些操作里会调用expungeStaleEntries方法,这个方法里会清理所有Key已经被回收的Entry。
Java代码  收藏代码
  1.    /** 
  2.     * Expunges stale entries from the table. 
  3.     */  
  4.    private void expungeStaleEntries() {  
  5. Entry<K,V> e;  
  6.        while ( (e = (Entry<K,V>) queue.poll()) != null) {  
  7.            int h = e.hash;  
  8.            int i = indexFor(h, table.length);  
  9.   
  10.            Entry<K,V> prev = table[i];  
  11.            Entry<K,V> p = prev;  
  12.            while (p != null) {  
  13.                Entry<K,V> next = p.next;  
  14.                if (p == e) {  
  15.                    if (prev == e)  
  16.                        table[i] = next;  
  17.                    else  
  18.                        prev.next = next;  
  19.                    e.next = null;  // Help GC  
  20.                    e.value = null//  "   "  
  21.                    size--;  
  22.                    break;  
  23.                }  
  24.                prev = p;  
  25.                p = next;  
  26.            }  
  27.        }  
  28.    }  
  29.   
  30.    /** 
  31.     * Returns the table after first expunging stale entries. 
  32.     */  
  33.    private Entry[] getTable() {  
  34.        expungeStaleEntries();  
  35.        return table;  
  36.    }  
  37.   
  38.    /** 
  39.     * Returns the number of key-value mappings in this map. 
  40.     * This result is a snapshot, and may not reflect unprocessed 
  41.     * entries that will be removed before next attempted access 
  42.     * because they are no longer referenced. 
  43.     */  
  44.    public int size() {  
  45.        if (size == 0)  
  46.            return 0;  
  47.        expungeStaleEntries();  
  48.        return size;  
  49.    }  

        基本上差异就是这些。WeakHashMap本身的特性也使它经常被应用到一些缓存的场景。
0 0
原创粉丝点击