...
This guards reads and writes to the flag
field with a lock on the instance, that is, this
. This compliant solution ensures that changes are visible to all the threads. It is also permissible to declare flag
as volatile
to ensure its visibility and while doing so, forgoing to synchronize the getFlag()
method. The toggle()
method still requires synchronization because it performs a non-atomic operation. However, this advanced technique is brittle in most other scenarios, such as, when a getter method performs operations other than just returning the value of the volatile
field.
Compliant Solution (java.util.concurrent.atomic.AtomicBoolean
)
...