Search code examples
javamultithreadingvolatile

How to comprehend - Locking is not required for any other reason while the variable is being accessed


From book "Java Concurrency in Practice" page 26:

You can use volatile variables only when all the following criteria are met:

  • Writes to the variable do not depend on its current value, or you can ensure that only a single thread ever updates the value;

  • The variable does not participate in invariants with other state variables

and

  • Locking is not required for any other reason while the variable is being accessed.

What's the meaning of the last bit?


Solution

  • The last point is the least technical one: it simply states that you need locks... if you need locks. It is here just for completeness in order to make the list as a whole comprehensive. You may need locks for any number of reasons which fall outside the scope of the memory visibility/atomicity aspects which are discussed in this section.