Rac*_*hel 2 java collections concurrency performance
码:
public class SlowDictionary {
private final Map<String,String> dict = new HashMap<String,String>();
public synchronized String translate (String word)
throws IllegalArgumentException {
if (!dict.containsKey(word)) {
throw new IllegalArgumentException(word + " not found.");
}
return dict.get(word);
}
public synchronized void addToDictionary (String word, String translation)
throws IllegalArgumentException {
if (dict.containsKey(word)) {
throw new IllegalArgumentException(word + " already exists.");
}
dict.put(word,translation);
}
public synchronized Set<String> getAllWords () {
return dict.keySet();
}
}
Run Code Online (Sandbox Code Playgroud)
你要做的第一件事是摆脱所有同步的关键词.
最简单的方法是将dict声明为ConcurrentHashMap:
private final ConcurrentMap<String,String> dict = new ConcurrentHashMap<String,String>();
Run Code Online (Sandbox Code Playgroud)
这样做你可以移除翻译的同步部分,所以它看起来像:
public String translate (String word) throws IllegalArgumentException { ..
Run Code Online (Sandbox Code Playgroud)
其原因是CCHM关于最新读数的合同.
最后,添加到字典可以看起来像:
public void addToDictionary (String word, String translation) throws IllegalArgumentException {
if (dict.putIfAbsent(word,translation)!=null) {
throw new IllegalArgumentException(word + " already exists.");
}
}
Run Code Online (Sandbox Code Playgroud)
同时从getAllWords中删除synchronized.
编辑:在思考汤姆的评论之后.在这个"例外情况"中进行双重查看可能不值得.如果案件没有抛出异常那么这是合适的.
| 归档时间: |
|
| 查看次数: |
542 次 |
| 最近记录: |