使用并发的Java性能

Rac*_*hel 2 java collections concurrency performance

  1. 如何提高这一块代码的性能?
  2. 给定问题陈述的单元测试案例是什么?

码:

    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)

Joh*_*int 6

你要做的第一件事是摆脱所有同步的关键词.

最简单的方法是将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.

编辑:在思考汤姆的评论之后.在这个"例外情况"中进行双重查看可能不值得.如果案件没有抛出异常那么这是合适的.

  • 我对'addToDictionary`实现感到困惑.您正在优化抛出异常的路径并将快乐路径的成本加倍? (3认同)