-1

I have just found HiddenInterator example, in the Java concurrency in practice book.

class ConcurentIterator implements Runnable {
    // because of final it is immutable, so it is thread safe
    private final Set<Integer> v = new HashSet<Integer>();
    //private final Vector<Integer> v = new Vector<Integer>();

    public synchronized void add(Integer i) {
        v.add(i);
    }

    public synchronized void remove(Integer i) {
        v.remove(i);
    }

    public void addTenThings() {
        Random r = new Random();
        for (int i = 0; i < 10; i++) {
            add(r.nextInt());
            System.out.println("DEBUG: added ten elements to " + v);
        }
    }

    public void run() {
        addTenThings();
    }
}

I understand everything! that's nice!

I have the following question:

In java we have concurrent collections for instance: ConcurentSkipListMap, ConcurrentHashMap, where the problem is fixed. But I'm interested which are the classes where the problem can happen(where it is not fixed)? For instance can it be occur on vector? When I was testing, I can't throw the ConcurentModificationException in the vector.

Testing method:

public static void main(String[] args) {

    Thread[] threadArray = new Thread[200];
    ConcurentIterator in = new ConcurentIterator();

    for (int i = 0; i < 100; i++) {
        threadArray[i] = new Thread(in);
    }

    for (int i = 0; i < threadArray.length; i++) {
        threadArray[i].start();
    }

}
4

1 回答 1

1

线程不安全集合会表现出这种抛出 ConcurrentModificationException 的行为——例如 Arraylist、HashSet、HashMap、TreeMap、LinkedList...

如果在迭代过程中更改了集合而不使用正在使用的迭代器,则像 vector 这样的线程安全集合也会表现出这种行为。

您在这里的目标是什么 - 知道可以抛出此异常的所有集合的名称;最好是专注于概念并以个别例子来展示概念。

在下面为使用 Vector 并且仍然会抛出 ConcurrentModificationException 的代码添加一个示例 - 想法是应该通过迭代器完成删除,否则集合将失败,发出同时尝试修改集合的信号

public static void main(String[] args) {
    Vector<Integer> numbers = new Vector<Integer>(Arrays.asList(new Integer[]{1,2,3,4,5,6}));
    for (Integer integer : numbers) {
        System.out.println(integer);
        numbers.remove(2);
    }
}
于 2015-03-23T08:11:09.423 回答