问题描述
关于Java并发的线程安全问题
具体疑问
在多线程环境下,成员变量类型为ArrayList,HashSet,LinkedHashSet,HashMap,LinkedHashMap的线程安全问题
public class Demo {
private final Collection<String> coll1=new ArrayList<>();
private final Collection<String> coll2=new HashSet<>();
private final Collection<String> coll3=new LinkedHashSet<>();
private final Map<String,String> map1= new HashMap<>();
private final Map<String,String> map2= new LinkedHashMap<>();
public Demo(String param) {
this.coll1.add(param);
this.coll2.add(param);
this.coll3.add(param);
this.map1.put(param,param);
this.map2.put(param,param);
//如果成员变量只定义未赋值在这里进行进行赋值初始化
//this.coll1= new ArrayList<String>(){{add(param);}};
//this.coll2= new HashSet<String>(){{add(param);}};
//this.coll3= new LinkedHashSet<String>(){{add(param);}};
//this.map1= new HashMap<String,String>(){{put(param,param);}};
//this.map2= new LinkedHashMap<String,String>(){{put(param,param);}};
}
public String byColl(int i){
return coll1.toArray(new String[0])[i];
//return coll2.toArray(new String[0])[i];
//return coll3.toArray(new String[0])[i];
}
public String byMap(String i){
return map1.get(i);
//return map2.get(i);
}
public void apply(Function<String,String> fn){
for (String s : coll1) {
fn.apply(s);
}
for (String s : coll2) {
fn.apply(s);
}
for (String s : coll3) {
fn.apply(s);
}
}
public Collection<String> getKeys(){
return Collections.unmodifiableSet(map1.keySet());
//return Collections.unmodifiableSet(map2.keySet());
}
//还有一些其他的读方法 比如size(),isEmpty()等
}
疑问
如果上例中用final修饰的成员变量ArrayList,HashSet,LinkedHashSet,HashMap,LinkedHashMap只在构造函数中进行集合的新增编辑操作,其他方法只会对成员变量进行读(get,keySet,values,size,foreach等)和使用迭代器,那么这个类是线程安全的吗?如果不是那么那些成员变量是存在线程安全问题的?
来源链接:https://www.cnblogs.com/51efan/p/18689461










没有回复内容