単語とそれに対応する整数インデックスをハッシュマップに保存する必要があります。ハッシュマップは同時に更新されます。
例:
ハッシュマップには次のキーと値のペアが含まれます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);
}
}
}
私の質問は、上記のクラスがスレッドセーフかどうかです。基本的に、この場合の不可分操作は、をインクリメントしmaxIndex
、単語がない場合はハッシュマップに単語を配置することです。
この状況で並行性を実現するためのより良い方法はありますか?