Java volatile for concurrency

前端 未结 2 353
逝去的感伤
逝去的感伤 2021-01-07 08:01

Ok so I just read this question Do you ever use the volatile keyword in Java?, and I get using a volatile variable in order to stop a loop. Also I\'ve seen this reference, h

相关标签:
2条回答
  • 2021-01-07 08:14

    No, reading a volatile variable is faster than than reading an non-volatile variable in a synchronized block.

    A synchronized block clears the cached values on entry which is the same as reading a volatile variable. But, it also flushes any cached writes to main memory when the synchronized block is exited, which isn't necessary when reading volatile variable.

    0 讨论(0)
  • 2021-01-07 08:30

    There's a numebr of things wrong in your question: You can do a reliable read-update-write with volatile so long as you use Atomic*FieldUpdater and a cas-loop. Volatiles can be "cached", they just need to obey the relevant happens-before semantics specified.

    Synchronisation typically involves obtaining a lock, which is relatively expensive (although may actually be quite cheap). Simple concurrent optimisations may use non-naive implementation techniques.

    0 讨论(0)
提交回复
热议问题