Conllection 同步 iterator 的问题
在一个多线程的程序里面 有一个
Collection list = new LinkedList();
在一个方法里面会调用
public void methodOne{
Iterator it = list.iterator();
while(it.hasNext()){
XX x = (XX)it.next();
//do something
}
}
另外的方法会使用
public void methodTwo{
synchronized(list){
list.add(sth);
}
}
我想问一下 除了把methodOne 函数或者函数内容加上 synchronized
eg:
1.public synchronized void methodOne(){
...
}
2.public void methodOne(){
Iterator it = list.iterator();
synchronzied(list){
while(it.hasNext()){
... ...
}
}
这两种方法来同步list 还有没有其他的方法来同步iterator了?
Colletions.synchronizedColleciton(xxx) 方法返回的Object 也不能同步iterator 必须要自己来保证.
我认为
synchronzied(list){
while(it.hasNext()){
... ...
}
会太影响性能了 因为有很多连接都在不停的查询
请问大家有没有好一点的 同步iterator的方法 Thx. :)