DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone >

Why Is This Not Thread Safe?

Oren Eini user avatar by
Oren Eini
·
Apr. 26, 11 · · News
Like (0)
Save
Tweet
4.18K Views

Join the DZone community and get the full member experience.

Join For Free
take a look at the following piece of code:

if(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:

image

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.

Implementation Doc (computing) Invariant (computer science)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • After COVID, Developers Really Are the New Kingmakers
  • Use Lambda Function URL To Write a Serverless App Backed by DynamoDB
  • Why Is Software Integration Important for Business?
  • How Database B-Tree Indexing Works

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo