英文:
java.util.ConcurrentModificationException with the presence of Locks
问题
以下是您要的代码部分的中文翻译:
我最初的设置如下:
LinkedList<Integer> ll;
Lock lock;
...
// 分配内存
ll = new LinkedList<Integer>();
lock = new ReentrantLock();
然后在一个计时器线程中,我有以下代码:
Integer example... // 在某处设置
lock.lock();
ll.addLast(example);
lock.unlock();
另一个计时器线程中,有以下代码:
ListIterator<Integer> ll_iter = new ll.listIterator();
while (ll_iter.hasNext()){
// 做一些操作
lock.lock();
ll_iter.remove();
lock.unlock();
}
当我运行时,我收到以下错误:
```java.util.ConcurrentModificationException```
这两个位置是唯一访问列表、添加或删除元素的地方。然而,我偶尔会收到上述错误。我找不到原因是什么?是因为迭代器吗?这两个锁都在计时器线程中(使用 Java Timer 的 run 方法、周期等)。
英文:
I have the following setup initially
LinkedList<Integer> ll;
Lock lock;
...
//memory is allocated
ll = new LinkedList<Integer>();
lock = new ReentrantLock();
Then in a Timer thread, I have the following
Integer example... //set somewhere before
lock.lock();
ll.addLast(example);
lock.unlock();
Another in another Timer thread, have the following
ListIterator<Integer> ll_iter = new ll.listIterator();
while (ll_iter.hasNext()){
//do something then
lock.lock();
ll_iter.remove();
lock.unlock();
}
I get the following error when running
java.util.ConcurrentModificationException
These two locations are the only places that the list is accessed, has anything added or removed. However, very sporadically, I get the following error. I can't find why this is happening? Is it because of the iterator? Both locks are in a timer threar (Java Timer with a run method, period etc).
专注分享java语言的经验与见解,让所有开发者获益!
评论