this question has answer here:
- do ever use volatile keyword in java? 19 answers
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
Post a Comment