Precise meaning and effects of volatile in Java? -


this question has answer here:

question inspired question @ why bufferedinputstream copy field local variable rather use field directly .

one of ansers says "volatile" keyword :

"also, declared volatile, means if thread changes value of variable, change reflected in other threads."

this seems suggest if variable not declared volatile, not case "change reflected in other threads", or iow, "changes variable reflected later".

questions :

(a) understanding correct ? (b) if so, when precisely are changes applied / exposed other threads ?

the java volatile keyword used mark variable / field being stored in main memory, , in more accurate words, every time variable accessed, read / written main computer memory , not / cpu cache.

in typical multi-threaded application, when many threads started, may make copy of non-voalatile variables main memory cpu cache, hence each thread have own copy of variable , done performance reasons. given that, there no guarantee @ when jvm either read of write non-volatile variable state / main memory.

the volatile keyword guarantees variable marked modifier written computer main memory.


Comments