1

In Java Concurrency book it is mentioned - The visibility effects of volatile variables extend beyond the value of the volatile variable itself. When thread A writes to a volatile variable and subsequently thread B reads that same variable, the values of all variables that were visible to A prior to writing to the volatile variable become visible to B after reading the volatile variable. So from a memory visibility perspective, writing a volatile variable is like exiting a synchronized block and reading a volatile variable is like entering a synchronized block.

So going by the above, alternative to volatile keyword is to use a synchronized getter method? I understand any update to volatile variable is propagated to all threads accessing it and also using volatile for read-only is better than using synchronized block as it does not perform expensive locking.

private volatile String shopName;

public boolean getShopName() {
    if (shopName == null) {
        synchronized(this) {
            if (shopName == null) {
                shopName = "abc";
            }
        }
    }
    return shopName;
}
  • Thanks, this has been answered by erickson here - https://stackoverflow.com/questions/3524775/java-volatile-for-concurrency. No, reading a volatile variable is faster than than reading an non-volatile variable in a synchronized block. A synchronized block clears the cached values on entry which is the same as reading a volatile variable. But, it also flushes any cached writes to main memory when the synchronized block is exited, which isn't necessary when reading volatile variable. – NJavalearner Apr 05 '18 at 19:15

0 Answers0