我有一个存储数据并从许多线程中调用的类。ConcurrentModificationException
尽管每次对我的访问Set
都是同步的,但它失败了。
这怎么可能发生?同步应确保我的 Set 在迭代时不会更改...
这是我班级中所有访问Set
...的函数
谁能告诉我这里出了什么问题?
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);
}
}
}