Hashtable 刪除元素, 拋出異常 java.util.ConcurrentModificationException

來源:互聯網
上載者:User

標籤:

今天在對一個Hashtable對象進行 搜尋 -> 刪除 操作時遇到的一個問題,開始的使用我使用的是Hashtable的Iterator,然後直接執行:

Hashtable.remove(key); 拋出異常  java.util.ConcurrentModificationException

 

查了一下java api doc,相關介紹如下:

 

由迭代器返回的 Iterator 和由所有 Hashtable 的“collection 視圖方法”返回的 Collection 的 listIterator 方法都是快速失敗的:在建立 Iterator 之後,如果從結構上對 Hashtable 進行修改,除非通過 Iterator 自身的移除或添加方法,否則在任何時間以任何方式對其進行修改,Iterator 都將拋出 ConcurrentModificationException。因此,面對並發的修改,Iterator 很快就會完全失敗,而不冒在將來某個不確定的時間發生任意不確定行為的風險。由 Hashtable 的鍵和值方法返回的 Enumeration不是快速失敗的。

 

 

Hashtable<Integer,Integer> t = new Hashtable<Integer,Integer>();
     
     for(int i=0;i<10;i++)
     {
      t.put(i,i*10);
     }   
     
     System.out.println("t.size():" + t.size());
     System.out.println(t.get(6));
     
     System.out.println();       
         
        Iterator<Integer> i = t.keySet().iterator();
     
     while(i.hasNext())
     {
      int key = i.next();
      
      if(key == 3)      
      {
       //t.remove(key);  //這樣刪除,拋出異常 java.util.ConcurrentModificationException       
       i.remove(); //只有這樣,才可以成功的刪除一個元素
      }
     }
     
     System.out.println("t.size():" + t.size());     
     System.out.println(t.get(6));

使用上面這種t.keySet().iterator();方式,如果在多線程情況下,也是會拋出 java.util.ConcurrentModificationException

在多線程並發的情況下,在增加、修改、刪除、遍曆時全加上 synchronized :

public synchronized void delKey(int key)
 {  
  Iterator<Integer> i = t.keySet().iterator();
  while(i.hasNext())
     {
      int abc = i.next();
      
      //t.remove(key); //拋出異常 java.util.ConcurrentModificationException
   
      if(abc == key)
       i.remove(); //只有這樣,才可以成功的刪除一個元素
     }     
 }

當在多線路中調用 delKey()時,必須在定義delKey()方法前使用:synchronized,以保證多線程調用安全。

 

---------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

其實還有一種更早的(更原始的)的安全方法,使用Enumeration,這種方式不管是在單線程還是在多線程中執行都是安全的(注意下面的特別說明):

Hashtable<Integer,Integer> t = new Hashtable<Integer,Integer>();
     
     for(int i=0;i<10;i++)
     {
      t.put(i,i*10);
     }    
     
     System.out.println("t.size():" + t.size());
     System.out.println(t.get(6));
     
     System.out.println();    
     
     Enumeration<Integer> e = t.keys();
     while(e.hasMoreElements())
     {
      int key = e.nextElement();
      
      if(key == 3)
      t.remove(key);
     } 
     
     System.out.println("t.size():" + t.size());     
     System.out.println(t.get(6));

 

特別注意:

雖然使用Enumeration來遍曆元素是安全執行緒的,高並發的情況下進行增加、修改、遍曆,也不會拋什麼異常,但如果在遍曆Enumeration的同時刪除裡面的一個元素雖不會拋出什麼異常,但結果可能不是你想像的:list = new Vector<String>();
  
  list.add("1");
  list.add("2");
  list.add("3");
  list.add("4");
  list.add("5");
  list.add("6");
  
  Enumeration<String> i = list.elements();
  while(i.hasMoreElements())
  {
   String str = i.nextElement();
   
   System.out.println(str);
   
   list.removeElement(str); //在這裡刪除
  }

//輸出結果:

1

3

5

我看到這個結果,我是真的很意外。

 

2011-04-18

 

Hashtable 刪除元素, 拋出異常 java.util.ConcurrentModificationException

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.