Over a million developers have joined DZone.

Why Is This Not Thread Safe?

Take a look at the following piece of code:

if(items.ContainsKey(key) == false)
        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.


The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}