java. util. ConcurrentModificationException 에 관 하여

java. util. ConcurrentModificationException 에 관 하여
자바 doc 이 클래스 에 대한 정의:
This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible. For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances. Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw this exception if this behavior is detected. Iterators that do this are known as fail-fast iterators, as they fail quickly and cleanly, rather that risking arbitrary, non-deterministic behavior at an undetermined time in the future. Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception.  Note that fail-fast behavior cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast operations throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: ConcurrentModificationException should be used only to detect bugs.
 이 이상 이 발생 한 원인: 수정 대상 을 병발 하고 대상 은 병발 수정 을 지원 하지 않 습 니 다.비교적 흔히 볼 수 있 는 것 은 다 중 스 레 드 가 병발 하거나 단일 스 레 드 가 집합 을 옮 겨 다 닐 때 집합 요 소 를 동시에 수정 하 는 것 이다.
예 를 들 면:
package com.doctor.java8;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * This program crashes by throwing java.util.ConcurrentModificationException. Why? Because the
 * iterators of ArrayList are fail-fast; it fails by throwing ConcurrentModificationException if it detects that
 * the underlying container has changed when it is iterating over the elements in the container. This behavior
 * is useful in concurrent contexts when one thread modifies the underlying container when another thread is
 * iterating over the elements of the container.
 * 
 * @author sdcuike
 *
 *         Created on 2016 3 6    10:24:21
 */
public class ModifyingList {

    /**
     * @param args
     */
    public static void main(String[] args) {
        List list = new ArrayList<>();
        list.add("one");
        list.add("two");
        Iterator iterator = list.iterator();

        while (iterator.hasNext()) {
            System.out.println(iterator.next());
            list.add("three");
        }

        // one
        // Exception in thread "main" java.util.ConcurrentModificationException
        // at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
        // at java.util.ArrayList$Itr.next(ArrayList.java:851)
        // at com.doctor.java8.ModifyingList.main(ModifyingList.java:24)

    }

}

CopyOnWriteArrayList
일반 집합 iterators 가 fail - fast 인 이상 방문 과 동시에 수정 하 는 장면 은 지원 되 지 않 습 니 다.그럼 병발 용기 CopyOn Write Array List 로
package com.doctor.java8;

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Modifying CopyOnWriteArrayList
 * 
 * Observe that the element “four” added three times is not printed as part of the output. This is because
 * the iterator still has access to the original (unmodified) container that had three elements. If you create a
 * new iterator and access the elements, you will find that new elements have been added to aList.
 * 
 * @author sdcuike
 *
 *         Created on 2016 3 6    10:32:39
 */
public class ModifyingCopyOnWriteArrayList {

    /**
     * @param args
     */
    public static void main(String[] args) {
        List list = new CopyOnWriteArrayList<>();
        list.add("one");
        list.add("two");
        list.add("three");

        Iterator iterator = list.iterator();

        while (iterator.hasNext()) {
            System.out.println(iterator.next());
            list.add("four");
        }
        // one
        // two
        // three
        System.out.println("============");
        iterator = list.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
        // one
        // two
        // three
        // four
        // four
        // four

    }

}
 
java.util.concurrent.CopyOnWriteArrayList
A thread-safe variant of java.util.ArrayList in which all mutative operations ( add , set , and so on) are implemented by making a fresh copy of the underlying array. 
CopyOn WriteArrayList 에서 데이터 조작 방법 을 수정 할 때 copy 는 새로운 내부 배열 구 조 를 사용 하고 원래 의 내부 배열 구조 에 영향 을 주지 않 습 니 다.새로운 데 이 터 를 방문 하려 면 바 텀 의 새로운 배열 구조의 iterator 를 다시 가 져 와 야 합 니 다. (위의 프로그램 참조)

좋은 웹페이지 즐겨찾기