If I have a variable from which multiple threads read and only one thread writes, do I need to have a lock around that variable? Would it crash if one thread tries to read and the other thread tries to write at the same time?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The concurrency concern is not crashing, but what version of the data you’re seeing.
if the shared variable is written atomically, it’s possible for one (reader) thread to read a stale value when you thought your (writer) thread had updated the variable. You can use volatile keywords to prevent your reader threads from reading a stale value in this situation.
if the write operation is not atomic (for example if it’s a composite object of some kind and you’re writing bits of it at a time, while the other threads could theoretically be reading it) then your concern would also be that some reader threads could see the variable in an inconsistent state. You’d prevent this by locking access to the variable while it was being written (slow) or making sure that you were writing atomically.
Writes to some types of fields are atomic but without a happens-before relationship that ensures correct memory ordering (unless you use
volatile); see this page for details.