...
Compliant Solution (synchronization)
This compliant solution synchronized the toggle()
method to ensure that the flag
is made guards reads and writes to the flag
field with a lock on the instance, i.e., this
. This is accomplished by declaring both methods to be synchronized
. This solution, via locking, ensures that changes are visible to all the program's threads.
Code Block | ||
---|---|---|
| ||
class Foo { private boolean flag = true; public synchronized void toggle() { flag ^= true; // same as flag = !flag; } public synchronized boolean getFlag() { return flag; } } |
...