I am little confused…
Is it true that reading\writing from several threads all except long and double are atomic operations and it’s need to use volatile only with long and double?
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.
It sounds like you’re referring to this section of the JLS. It is guaranteed for all primitive types — except
doubleandlong— that all threads will see some value that was actually written to that variable. (Withdoubleandlong, the first four bytes might have been written by one thread, and the last four bytes by another thread, as specified in that section of the JLS.) But they won’t necessarily see the same value at the same time unless the variable is markedvolatile.Even using
volatile,x += 3is not atomic, because it’sx = x + 3, which does a read and a write, and there might be writes toxbetween the read and the write. That’s why we have things likeAtomicIntegerand the other utilities injava.util.concurrent.