Java 故障安全迭代器
我对故障安全迭代器的了解是,它创建原始数据结构的副本并对其进行迭代以允许并发修改。 我有一些困惑,比如:Java 故障安全迭代器,java,iterator,concurrenthashmap,Java,Iterator,Concurrenthashmap,我对故障安全迭代器的了解是,它创建原始数据结构的副本并对其进行迭代以允许并发修改。 我有一些困惑,比如: 修改是如何反映回原始数据结构的 如果我们有两个线程: 线程A:迭代器1删除一个元素(元素A) 线程B:迭代器2已开始迭代。如何向该迭代器传递原始DS已更改的信息 不能修改正在迭代的集合(concurent modification)。如果修改集合中的对象,它们也将在原始集合中修改 它将不会被传达。您正在迭代一个副本。如果您试图修改集合,请参见1 不能修改正在迭代的集合(concurent m
public class FailSafeIteratorExample {
public static void main(String[] args) {
// Creating a ConcurrentHashMap
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
// Adding elements to map
map.put("abc", 1);
// Here, we are working on clone copy.
Iterator<String> it = map.keySet().iterator();
while (it.hasNext()) {
String key = (String) it.next();
System.out.println(key + " : " + map.get(key));
map.put("mno", 2); // This will not be reflected in the Iterator
}
System.out.println("\n\n");
// Another clone copy just created with latest changes.
// This will print the existing element with newly added element("mno")
it = map.keySet().iterator();
while (it.hasNext()) {
String key = (String) it.next();
System.out.println(key + " : " + map.get(key));
}
}}
公共类故障保护迭代器示例{
公共静态void main(字符串[]args){
//创建ConcurrentHashMap
ConcurrentHashMap=新的ConcurrentHashMap();
//向地图添加元素
地图放置(“abc”,1);
//在这里,我们正在研究克隆拷贝。
迭代器it=map.keySet().Iterator();
while(it.hasNext()){
String key=(String)it.next();
System.out.println(key+”:“+map.get(key));
put(“mno”,2);//这不会反映在迭代器中
}
System.out.println(“\n\n”);
//刚刚用最新更改创建的另一个克隆副本。
//这将使用新添加的元素(“mno”)打印现有元素
it=map.keySet().iterator();
while(it.hasNext()){
String key=(String)it.next();
System.out.println(key+”:“+map.get(key));
}
}}