Java -- WeakHashMap

來源:互聯網
上載者:User

標籤:

一、引言

  Java中的參考型別由四種情況,強引用、軟引用、弱引用、虛引用。關於這些的介紹可以參見鄙人另外一篇博文。                                                                                                                                              http://www.cnblogs.com/plxx/p/4217178.html 

二、概述

  WeakHashMap,在家族中和HashMap是同輩的。

public class WeakHashMap<K,V>  extends AbstractMap<K,V>  implements Map<K,V>

   針對WeakHashMap --- An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use.當key不再使用的時候,就會被自動清除。不再使用是個什麼狀態???當GC root 枚舉不到的時候,就是認為此時可以被GC(finalizable -->finalized -->reclaimed 參閱)。

  同HashMap一樣,WeakHashMap允許<key,value>都為null,初始大小為16,load factor為0.75,不是安全執行緒的。

Once such a key is discarded it can never be recreated, so it is impossible to do a lookup of that key 
in a WeakHashMap at some later time and be surprised that its entry has been removed.

  一旦Key被清除,就不可以再被建立,查詢,稍後entry就會被移除。

Each key object in a  WeakHashMap  is stored indirectly as the referent of a weak reference. 
value objects do not strongly refer to their own keys, either directly or indirectly,
since that will prevent the keys from being discarded

   其中的key存放的是weak reference.而value中存放的是strong reference,value不知直接或者間接地和key發生關聯,否則會阻止key的清除。

三、查看源碼

 1  private void expungeStaleEntries() { 2         for (Object x; (x = queue.poll()) != null; ) { 3             synchronized (queue) { //將隊列加鎖控制 4                 @SuppressWarnings("unchecked") 5                     Entry<K,V> e = (Entry<K,V>) x; 6                 int i = indexFor(e.hash, table.length); 7  8                 Entry<K,V> prev = table[i]; //找到實體所在的桶號 9                 Entry<K,V> p = prev;
            //找到這個實體10 while (p != null) {11 Entry<K,V> next = p.next;12 if (p == e) {13 if (prev == e)14 table[i] = next;15 else16 prev.next = next;17 // Must not null out e.next;18 // stale entries may be in use by a HashIterator19 e.value = null; // Help GC20 size--;21 break;22 }
               //移除該實體--不可恢複23 prev = p;24 p = next;25 }26 }27 }28 }

  expunge - Stale -  Entries 擦除 陳舊 實體

  在resize(),size(),getTables()的相關操作中都會調用該方法。將不使用的對象統統擦除。

Java -- WeakHashMap

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.