0

Question inspired by the question at Why does BufferedInputStream copy a field to a local variable rather than use the field directly .

One of the ansers says this about the "volatile" keyword :

"Also, it is declared volatile, which means that if any thread changes the value of the variable, this change will immediately be reflected in all other threads."

This seems to suggest that if a variable is NOT declared volatile, then it will not be the case that "change will immediately be reflected in all other threads", or IOW, "changes to the variable will be reflected only later".

Questions :

(a) is that understanding correct ? (b) If so, when precisely ARE changes then applied / exposed to other threads ?

Community
  • 1
  • 1
Erwin Smout
  • 18,113
  • 4
  • 33
  • 52

1 Answers1

2

The Java volatile keyword is used to mark a variable / field as being stored in main memory, and in more accurate words, every time the variable is accessed, it is read / written to the main computer memory and not from / to the CPU cache.

In a typical multi-threaded application, when many threads are started, they may make a copy of a non-voalatile variables from the main memory to the CPU cache, hence each thread will have its own copy of the variable and this is mainly done for performance reasons. Given that, there is no guarantee at when the JVM will either read back of write back the non-volatile variable state from / to main memory.

The volatile keyword guarantees that a variable marked with this modifier will be written to the computer main memory.

tmarwen
  • 15,750
  • 5
  • 43
  • 62