Java volatile for concurrency

送分小仙女□ 提交于 2019-12-01 01:11:54

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!