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 ?
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.
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.
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...
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With