multithreading - Does java.util.concurrent.ConcurrentHashMap.putIfAbsent need to be in a syncronized block? -
i trying track down race condition , signs seem pointing concurrenthashmap.putifabsent()
. possible if 2 threads call putifabsent()
on empty map same key both lookup see key not exist yet both threads try add it? reason when first started using putifabsent()
did not think call need synchronized. can't see how prevent both threads adding values if timing right. have not been able reproduce outside of production.
thanks
none of operations concurrent collection needs use synchronized.
this design , in fact locking collection has no effect on other operations. (unless locked well) in case make them slower.
is possible if 2 threads call putifabsent() on empty map same key both lookup see key not exist yet both threads try add it?
both can try, 1 succeed. not possible 2 threads appear have succeeded.
for reason when first started using putifabsent() did not think call need synchronized.
it doesn't.
but can't see how prevent both threads adding values if timing right.
it performs cas operation in code means 1 operation can succeed , thread know one. cas operation doesn't need locking uses underlying assembly instruction perform this. in fact implement lock using cas operation, rather other way around.
Comments
Post a Comment