...
The second execution order involves the same operations, just that t2 starts and finishes before t1.
Compliant Solution (
...
volatile-read, synchronized-write
...
)
It is also permissible to declare flag
as volatile
to ensure its visibility and while doing so, forgoing to synchronize In this compliant solution, the getFlag()
method is not synchronized and flag
is declared as volatile. This is compliant because the read of flag
in the getFlag()
method is an atomic operation and the volatile qualification assures visibility. The toggle()
method still requires synchronization because it performs a non-atomic operation.
Code Block | ||
---|---|---|
| ||
final class Flag { private volatile boolean flag = true; public synchronized void toggle() { flag ^= true; // Same as flag = !flag; } public boolean getFlag() { return flag; } } |
Wiki Markup |
---|
This advancedapproach techniquemay isnot fragile in most other scenarios, such as,be used when a getter method performs operations other than just returning the value of thea {{volatile}} field. Thethat cheap read-write lock trick offers performance advantages because the method to read a value {{getFlag()}} is not synchronizedrequire synchronization. Unless read performance is critical, this methodtechnique ismay not recommended. offer significant advantages over synchronization \[[Goetz 06|AA. Java References#Goetz 06]\]. |
The cheap volatile-read, synchronized-write lock trick pattern is also addressed in CON11-J. Do not assume that declaring an object reference volatile guarantees visibility of its members.
...