The reason here is to protect against any other thread updating the value when the stream is reading, and thus avoid doing anything with an outdated value.
Here, the get method will get an internal lock on "this", and thus, any other thread that might try to set / update using the setter method will have to wait to get a lock on "this" in order to introduce the setter method, which is already received Stream execution in progress.
That is why it is recommended to adhere to the practice of using the same lock when performing any operation in a mutable state.
Creating field volatile will work here since there are no compound statements.
It is important to note that synchronized methods use the built-in lock "this". So, get and establish that both are synchronized, means that any thread entering the method will have to block it.
When performing non-atomic 64-bit operations, special care should be taken. Excerpts from Java Concurrency In practice, it may help here to understand the situation -
"The Java memory model requires that the retrieval and storage operations be atomic, but for non-volatile long and double variables, the JVM is allowed to treat 64-bit read or write as two separate 32 bits. If the read and write occur in different streams, so long-term long-term read information and return high 32 bits of one value and the lower 32 bits of another.Thus, even if you do not need obsolete values, it is unsafe to use common modified long and double variables in multi-threaded ogrammah, if they are not fragile or protected lock. "
Upendra Upadhyay Apr 22 '14 at 7:37 2014-04-22 07:37
source share