我必须将单词及其相应的整数索引存储在哈希图中。哈希映射将同时更新。
例如:假设wordList
是{a,b,c,a,d,e,a,d,e,b}
哈希映射将包含以下键值对
a:1
b:2
c:3
d:4
e:5
代码如下:
public class Dictionary {
private ConcurrentMap<String, Integer> wordToIndex;
private AtomicInteger maxIndex;
public Dictionary( int startFrom ) {
wordToIndex = new ConcurrentHashMap<String, Integer>();
this.maxIndex = new AtomicInteger(startFrom);
}
public void insertAndComputeIndices( List<String> words ) {
Integer index;
//iterate over the list of words
for ( String word : words ) {
// check if the word exists in the Map
// if it does not exist, increment the maxIndex and put it in the
// Map if it is still absent
// set the maxIndex to the newly inserted index
if (!wordToIndex.containsKey(word)) {
index = maxIndex.incrementAndGet();
index = wordToIndex.putIfAbsent(word, index);
if (index != null)
maxIndex.set(index);
}
}
}
我的问题是上面的类是否是线程安全的?基本上,在这种情况下,原子操作应该是递增 the maxIndex
,然后如果不存在该单词则将其放入哈希映射中。
在这种情况下有没有更好的方法来实现并发?