Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what happens after writing to a volatile variable?

Tags:

java

volatile

I wonder if writing to a volatile variable will force jvm to synchronize all non-volatile variables to the memory, so for example, what will happen in the following code:

volatile int x;
int y;

y=5; 
x=10;

x will be written to the memory, but what will happen to y ? will it be also written to memory ?

like image 314
Anonymice Avatar asked Aug 20 '11 01:08

Anonymice


People also ask

What happens when you write to a volatile variable in Java?

Any write to volatile variable in Java establishes a happen before the relationship with successive reads of that same variable. The volatile variables are always visible to other threads.

Why are changes to a volatile variable always visible to other threads?

It means that changes to a volatile variable are always visible to other threads. Every read of a volatile variable will be read from the computer’s main memory, and not from the CPU cache. Similarly, every write to a volatile variable will be written to main memory, and not to the CPU cache.

What are the advantages of using volatile keyword with variables?

Important points 1 You can use the volatile keyword with variables. ... 2 It guarantees that value of the volatile variable will always be read from the main memory, not from the local thread cache. 3 If you declared variable as volatile, Read and Writes are atomic 4 It reduces the risk of memory consistency error. Mai multe articole...

What is the use of volatile in C++?

The exact use of a volatile keyword or variable changes with regard to a particular programming language syntax, but generally, variables can be created as volatile, or conditionally declared volatile within code. One popular use of the volatile keyword for a variable is in writing code to end a loop or terminate a thread.


1 Answers

Yes, under the rules of the Java Language Specification (third edition) -- in particular section 17.4.4 -- every thread that sees the new value of x will subsequently also see the new value of y if they try to read it. Threads that don't read x are not guaranteed to be affected.

Beware, however, that this guarantee was not present in the memory model of the second edition of JLS. There, volatile reads and writes had no effect on the ordering of non-volatile memory accesses.

like image 169
hmakholm left over Monica Avatar answered Oct 17 '22 22:10

hmakholm left over Monica