This is a section from Core Java 8th edition Page 757
CAUTION:
public void flipDone() {
done = !done;
}
// not atomic
I don’t understand why it’s not atomic. Can any one tell me why? thanks
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
flipDonemethod is executed by the computer in three distinct steps:In Java, a piece of code can potentially be invoked in multiple threads. These threads should be thought of as executing the code concurrently.
Say, memory location labeled
donecontains the valuefalseinitially. Consider two threads callingflipDone, resulting in the following sequence of steps:The
flipDonemethod was called twice.donewent fromfalsetotrueand then back again tofalse– as one would expect. But since the threads execute concurrently, this is not the only ordering of steps. Consider this ordering instead:While the first thread is inverting the value it read, the second thread, concurrently, is reading the value. Similarly, while the first thread is writing the value to memory, the second thread is inverting the value it read. When
Thread 2finishes, the value ofdonewill be true. Here, althoughflipDonewas called twice,donewas flipped only once! One of the updates seem to have been lost. This is the problem that the book is trying to warn you about.