本文介绍了如何使用ConcurrentModificationException对Set上的同步迭代失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个存储数据的类,并从许多线程调用。它失败并带有 ConcurrentModificationException 虽然我对 Set 的每次访问都是同步的。

I have a class which stores data and gets called from many threads. It fails with a ConcurrentModificationException although every access to my Set is synchronized.

这怎么可能发生? synchronized应该确保我的Set在迭代时不会被更改...

How can this happen? The synchronized should make sure that my Set is not changed while it is iterated...

以下是我班级中访问 Set的所有函数 ...

Here are all functions from my class that access the Set...

谁能告诉我这里出了什么问题?

Can anyone tell me what is going wrong here?

private final Object mListenerLock = new Object();
private final Set<IRetainerBaseListener> mListeners = new HashSet<IRetainerBaseListener>();

protected final void register(IRetainerBaseListener listener)
{
    synchronized (mListenerLock)
    {
        mListeners.add(listener);
    }
}

protected final boolean unregister(IRetainerBaseListener listener)
{
    synchronized (mListenerLock)
    {
        return mListeners.remove(listener);
    }
}

private final void onObjectAdded(RKey key, Object data)
{
    synchronized (mListenerLock)
    {
        Iterator<IRetainerBaseListener> it = mListeners.iterator();
        while (it.hasNext())
        {
            IRetainerBaseListener listener = it.next();

            /* EDIT */
            /* I'm not changing the Set in here, never!!! */

            // I can't insert the if's, but I just check the interface class
            // and call one of the following methods:

            ((IRetainerListener) listener).onRetainerDataAdded(key, data);
            // or
            ((IRetainerSingleKeyListener) listener).onRetainerDataAdded(data);

        }
    }
}


推荐答案

这不是线程安全的问题。

It's not a problem of thread safety.

您在迭代集合时删除项目。这只能使用迭代器

You are removing items while iterating on your collection. This is only possible using an iterator.

 /*
  * *it* does not appreciate that you removed elements 
  * in another way than it.remove();
  * The iterator must do the add/remove operations itself
  * to guarantee that it will not break the iteration.
  */
 while (it.hasNext()) {
   IRetainerBaseListener listener = it.next();
   ...
 }

这篇关于如何使用ConcurrentModificationException对Set上的同步迭代失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 15:19