Charles Wang
Charles Wang

Reputation: 11

HashMap, maybe atomic when get, and the key is guaranteed already put completely

my code:

class Pair {
    public String key;
    public String value;
}
Iterator<Pair> pairs;
HashMap<String, String> map = new HashMap<String, String>();
while (pairs.hasNext()) {
    Pair p = pairs.next();
    map.put(p.ket, p.value)
    // then put p.key to another thread for RPC
    // after returned, lookup the hashmap, join the result and p.value, and output 
}

After each RPC finished, the thread pool will lookup the hashmap, to join the RPC result and value for the key. Is this atomic ?

Upvotes: 0

Views: 455

Answers (1)

Francis Upton IV
Francis Upton IV

Reputation: 19443

No, the HashMap class is not thread safe. You will need to add additional synchronization.

Upvotes: 3

Related Questions