Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is a volatile variable synchronized? (java)

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?

like image 249
yotamoo Avatar asked May 22 '11 16:05

yotamoo


People also ask

Is volatile variable synchronized?

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.

Is volatile needed with synchronized?

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.

Can volatile replace synchronized?

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.

Does synchronization techniques are required for volatile variable?

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.


1 Answers

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.

like image 64
Ernest Friedman-Hill Avatar answered Oct 22 '22 05:10

Ernest Friedman-Hill