if(concurrentHashMap.containKey(key))
{
// oops, v has been removed in another thread right after current thread
// complete containKey calling
Value v = concurrentHashMap.get(key);
// do something on v // null pointer exception
}
It seems concurrent collection’s contain-like method is useless, to fix above problem:
Vaule v = concurrentHashMap.get(key);
if(v != null)
{
// ok, hold v's reference
// do something on v
}
Am I right?
As stated in the comment thread: no,
containsKeydoes not keep the entry locked in any way, so a later call toget(key)might returnnull. That said, if you’re only interested in the boolean — is the key in the map? — and you don’t need to get the key later on, thencontainsKeyis fine.Additionally,
containsKeyis required by theMapinterface, so it’s not like it wouldn’t be there anyway.