Say that I have a private variable and I have a setVariable()
method for it which is synchronized
, isn't it exactly the same as using volatile
modifier?
The volatile keyword is a lightweight synchronization mechanism. Unlike synchronized methods or blocks, it does not make other threads wait while one thread is working on a critical section.
If it is accessed only from synchronized blocks is not needed the volatile keyword. Synchronized guarantees that changes to variables accessed inside the synchronized block are visible to all threads entering a synchronized block.
It basically means that all changes to other variables that happen before the line of execution hits a volatile variable will be flushed back to the Main Memory. The same thing happens when the line of execution hits Synchronized block. That is why Volatile and Synchronized are considered to be almost the same.
If there's a single thread that writes to the volatile variable and other threads only read the volatile variable then just using volatile is enough, however, if there's a possibility of multiple threads writing to the volatile variable then “synchronized” would be required to ensure atomic writes to the variable.
No. Volatile means the variable isn't cached in any per-thread cache, and its value is always retrieved from main memory when needed. Synchronization means that those per-thread caches will be kept in sync at certain points. In theory, using a volatile variable can come with a great speed penalty if many threads need to read the value of the variable, but it is changed only rarely.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With