Joh*_*per 0 java multithreading thread-safety
以下代码有什么问题?
private Map<Integer, Integer> aMap = new ConcurrentHashMap<Integer, Integer>();
Record rec = records.get(id);
if (rec == null) {
rec = new Record(id);
records.put(id, rec);
}
return rec;
Run Code Online (Sandbox Code Playgroud)
putIfAbsent在这种情况下我为什么要在这里使用?这不是线程安全的.
如果有另一个线程,那么在它之间的时间records.get和records.put其他线程可能也放置了记录.
只读操作(即不修改结构的操作)可以由多个线程同时完成.例如,1000个线程可以安全地读取a的值int.但是,如果int没有某种锁定操作,那1000个线程无法更新值.
我知道这可能听起来像是一个非常不可能发生的事件,但请记住,1百万分之一的事件在1GHz时每秒发生1000次.
这是线程安全的:
private Map<Integer, Integer> aMap = new ConcurrentHashMap<Integer, Integer>();
// presumably aMap is a member and the code below is in a function
aMap.putIfAbsent(id, new Record(id))
Record rec = records.get(id);
return rec;
Run Code Online (Sandbox Code Playgroud)
请注意,这可能会创建一个Record从不使用它.
| 归档时间: |
|
| 查看次数: |
79 次 |
| 最近记录: |