...
Wiki Markup |
---|
The {{toggle()}} method still requires synchronization because it performs a non-atomic operation. However, this advanced technique is brittlefragile in most other scenarios, such as, when a getter method performs operations other than just returning the value of the {{volatile}} field. The cheap read-write lock trick offers performance advantages sincebecause the method to read a value {{getFlag()}} is not synchronized. Unless read performance is critical, this method is not recommended. \[[Goetz 06|AA. Java References#Goetz 06]\] |
...
For example, when a thread is executing setValues()
another may invoke getSum()
and retrieve an incorrect result. Furthermore, in the absence of synchronization, there are data races in the check for integer overflow. For instance, a thread can call setValues()
after a second thread has read a
, but before it has read b
in order to add them together; in which case, the second thread will get an improper additionsum. Even worse, a thread can call setValues()
after a second thread has verified that overflow will not occur, but before the second thread reads the values to add. This would cause the second thread to add two values that have not been checked for overflow, and overflow when adding them.
...