【发布时间】:2012-07-13 19:12:36
【问题描述】:
我正在编写用于文本处理的代码,如果我先将字符串转换为整数,事情会变得快很多。为此,我创建了一个 Dictionary 类,每次我看到一个新字符串时,我都会给它一个索引,并保留两个映射,一个从 string 到 int,一个从 int 到 string,所以我可以轻松地查找两种方式.代码如下:
class Dictionary {
private Map<String, Integer> map;
private Map<Integer, String> reverse_map;
private int nextIndex;
public Dictionary() {
map = new HashMap<String, Integer>();
reverse_map = new HashMap<Integer, String>();
nextIndex = 1;
}
public int getIndex(String string) {
if (!map.containsKey(string)) {
map.put(string, nextIndex);
reverse_map.put(nextIndex, string);
nextIndex++;
}
return map.get(string);
}
public String getString(int index) {
// getIndex is always called first, so we don't need to check anything
return reverse_map.get(index);
}
}
这在我的单线程代码中运行良好。但现在我想给这个多个线程以加快速度,我不知道该怎么做。我想过使用 ConcurrentHashMap,但我不确定putIfAbsent 是否能保证我不会两次使用索引。我不想使用 Collections.synchronizedMap,因为这个字典在线程之间被非常频繁地访问,所以我可能不会比使用单个线程更好,因为它在每次读取和写入时都会阻塞。有没有办法让这个工作?
【问题讨论】:
-
hmm,所以您只需要插入/获取,并且密钥是自行生成的(即增量?),如果是这样,即使同时并发也可以使算法更快
标签: java concurrency hashmap concurrenthashmap