java - HashTable有沒有采用快速失敗機制?
問題描述
1,http://www.yq1012.com/api/jav...由所有類的“collection 視圖方法”返回的 collection 的 iterator 方法返回的迭代器都是快速失敗 的:在創建 Iterator 之后,如果從結構上對 Hashtable 進行修改,除非通過 Iterator 自身的 remove 方法,否則在任何時間以任何方式對其進行修改,Iterator 都將拋出ConcurrentModificationException。因此,面對并發的修改,Iterator 很快就會完全失敗,而不冒在將來某個不確定的時間發生任意不確定行為的風險。由 Hashtable 的鍵和元素方法返回的 Enumeration 不 是快速失敗的。
有地方說因為HashTable做了線程同步,所以沒有采用快速失敗機制
2,但是源碼中hashtable.keySet.iterator 返回的iterator中有 做判斷比如說iterator的remove方法 (在類: private class Enumerator<T> implements Enumeration<T>, Iterator<T>中)
public void remove() { if (!iterator)throw new UnsupportedOperationException(); if (lastReturned == null)throw new IllegalStateException('Hashtable Enumerator'); if (modCount != expectedModCount)throw new ConcurrentModificationException(); synchronized(Hashtable.this) {Entry[] tab = Hashtable.this.table;int index = (lastReturned.hash & 0x7FFFFFFF) % tab.length;for (Entry<K,V> e = tab[index], prev = null; e != null; prev = e, e = e.next) { if (e == lastReturned) {modCount++;expectedModCount++;if (prev == null) tab[index] = e.next;else prev.next = e.next;count--;lastReturned = null;return; }}throw new ConcurrentModificationException(); }} public T next() { if (modCount != expectedModCount)throw new ConcurrentModificationException(); return nextElement();}
上面兩端代碼中都有驗證 if (modCount != expectedModCount)
throw new ConcurrentModificationException();所以多線程環境下并發修改hashtable 也是會引起Iterator迭代失敗,我代碼測試過
這個該怎么理解,請問上面提到的哪種情況是正確的
問題解答
回答1:Hashtable的iterator遍歷方式支持fast-fail,用Enumeration不支持fast-fail
相關文章:
1. docker 下面創建的IMAGE 他們的 ID 一樣?這個是怎么回事????2. 在應用配置文件 app.php 中找不到’route_check_cache’配置項3. javascript - 關于mongose刪除一次多個字段的問題4. 微信瀏覽器怎么取消緩存?5. javascript - vue-cli與后端框架集成config/index.js配置問題6. javascript - 為什么我無法通過$stateParams在父子State之間傳遞參數?跟State之間的父子關系有關嗎?7. 關于layuiadmin中表格按鈕提交問題求解!!!!8. html按鍵開關如何提交我想需要的值到數據庫9. css - BEM 中塊(Block)有木有什么標準 何時決定一個部分提取為塊而不是其父級的元素呢(Element)?~10. html5 - 用Egret寫的小游戲,怎么分享到微信呢?
