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;
}