Search code examples
javamultithreadingvolatilesynchronized

when use synchronized to lock write, if need volatile to guard to avoid the read old value or not full value?


as titled. I have use synchronized to guard multi-thread write. but I want know if I need add volatile to guard read . (as we know, I can use synchronized to guard read too, but it will prevent read and write concorrently. what' more ,if I use reentraent lock. it will prevent too.)

private volatile BigDecimal cacheMiss = BigDecimal.ZERO;

public  BigDecimal getCacheHit() {
    return cacheHit;
}

public void increaseCacheMiss() {
    synchronized (cacheMissLock) {
        this.cacheMiss = this.cacheMiss.add(STEP);
    }
}

Solution

  • If cacheMiss can be updated from several threads, then it needs to be declared volatile if you absolutely need to read the latest value. Otherwise a thread may be reading a thread-local value (stashed in a register or core cache), not bothering to go out to main memory to see the latest value.