Why Is This Not Thread Safe?
Join the DZone community and get the full member experience.
Join For Freeif(items.containskey(key) == false) { lock(items) { if(items.containskey(key) == false) { items.add(key, val); } } }
the answer is quite simple, and it is located directly in the docs:
yes, on the face of it, this is safe code, in the sense that we will never get duplicatekeyexception. but the implementation of containskey() isn’t safe to run when add() is also executing.
the actual behavior depends on the implementation, but it is easy enough to imagine a scenario where invariants that containskey() relies on are broken for the duration of the add() call.
Opinions expressed by DZone contributors are their own.
Comments