gpt4 book ai didi

使用并发的 Java 性能

转载 作者:行者123 更新时间:2023-12-02 14:14:07 25 4
gpt4 key购买 nike

  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();
}
}

最佳答案

您要做的第一件事就是删除所有同步关键字。

最简单的方法是将 dict 声明为 ConcurrentHashMap:

private final ConcurrentMap<String,String> dict = new ConcurrentHashMap<String,String>();

这样做,您可以立即删除翻译的同步部分,使其看起来像:

 public String translate (String word) throws IllegalArgumentException { ..

原因是 CCHM 持有有关最新读取的契约(Contract)。

最后,添加到字典可以如下所示:

 public void addToDictionary (String word, String translation) throws IllegalArgumentException {
if (dict.putIfAbsent(word,translation)!=null) {
throw new IllegalArgumentException(word + " already exists.");
}
}

同时从 getAllWords 中删除同步。

编辑:在考虑了汤姆的评论之后。在这种“异常情况”中进行双重查找可能不值得。如果案例没有抛出异常,那么它是合适的。

关于使用并发的 Java 性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3443688/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com