Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java volatile and cache coherence

Tags:

java

volatile

If cache coherency is implemented at hardware level why do we need volatile? Any core/processor should get the latest value anyway?

Or is it dealing with a different issue completely?

like image 223
sab Avatar asked Jan 15 '14 04:01

sab


People also ask

What is Coherence cache in Java?

In computing, Oracle Coherence (originally Tangosol Coherence) is a Java-based distributed cache and in-memory data grid.

Does volatile invalidate cache?

ANSWER: No, volatile doesn't guarantee no caching for this memory location, and there aren't anything about this in C/C++ Standards or compiler manual.

What is Java volatile?

For Java, “volatile” tells the compiler that the value of a variable must never be cached as its value may change outside of the scope of the program itself.

Is volatile variable in Java thread safe?

Unlike synchronized methods or blocks, it does not make other threads wait while one thread is working on a critical section. Therefore, the volatile keyword does not provide thread safety when non-atomic operations or composite operations are performed on shared variables.


1 Answers

Cache coherence may be implemented at the processor level but, unless the processor memory model guarantees sequential consistency (which is not the case on most modern architectures), you will only get cache coherence if you ask for it.

That is what volatile is for: it asks the JVM to produce the relevant machine instruction(s) that will ask the processor(s) to synchronize its cache with main memory.

like image 77
assylias Avatar answered Oct 02 '22 08:10

assylias