Bober02
Bober02

Reputation: 15351

Java - volatile and visibility

As far as I have read, the underlying mechanism behind volatile guarantees no reordering of operations. However I am struggling to see how it guarantees visibility.

I.e. thread A writes a value. Then thread B reads it from memory, not from cache (to guarantee cache consistency). I know CAS does precisely this, but how does a memory barrier achieve this?

Upvotes: 3

Views: 143

Answers (3)

SergeyA
SergeyA

Reputation: 62613

Generic memory barrier is a CPU-specific instructions, which says 'invalidate your read cache' or 'commit your write cache', or both. On strong-ordering CPUs like x86 there 'invalidate your read cache' is a no-op, since caches are always coherent.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533870

The memory barrier is implemented by the CPU to always show the latest value. This cannot be achieved without CPU support.

It is a common misconception that access is to main memory, however this would be very slow. Instead there is a cache coherence bus between L2 caches.

There is a write store buffer before the L1 cache, but the CPU makes sure the cache line is current between cores.

Upvotes: 1

dezhik
dezhik

Reputation: 1030

Volatile "uses" hardware specific instructions to achieve it. Here is in-depth article about JSR-133 and Memory Barriers for Compiler Writers

I know CAS does precisely this, but how does a mem barrier achieve this?

Because if you look for example inside AtomicInteger, you'll see

private volatile int value;

Upvotes: 2

Related Questions