同步類容器並發修改的問題

來源:互聯網
上載者:User

標籤:成員   cep   throw   remove   return   equal   pre   次數   ica   

1、同步類容器都是安全執行緒的,在某些情境下需要加鎖來保護複合操作。
2、常見的複合操作有:迭代(反覆訪問元素,遍曆容器中所有元素)、跳轉(根據指定的順序找到當前元素的下一個元素)、以及條件運算等。
3、在這些複合操作下,進行並發的修改(add或remove)容器時,會拋出java.util.ConcurrentModificationException異常。在早期的迭代器設計的時候並沒有考慮並發修改的問題。
...
Vector v = new Vector<>();
v.add("1");
v.add("2");
v.add("3");
...

 public Collection<String> m2(Vector<String> list) {    Iterator<String> iterator = list.iterator();    while (iterator.hasNext()) {        String temp = iterator.next();        if ("3".equals(temp)) {            list.remove(temp);        }    }    return list;}

4、閱讀源碼可以看到,在AbstractList類裡面定義有成員變數modCount(修改次數)和expectedModCount(期望修改次數,初始值為modCount),在多線程並發下修改時候會出現這兩個值不相等,而拋出ConcurrentModificationException異常。

    final void checkForComodification() {        if (modCount != expectedModCount)            throw new 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.