Java volatile and side-effects

南笙酒味 提交于 2019-12-02 19:47:43

Most multiprocessor caches have coherency mechanisms, so the penalty isn't as bad as flushing all the caches.

Any writes in the thread that wrote to the volatile before doing so will be seen by the thread reading the volatile after having done so.

Take Double Checked Locking as an example. When you create an object, many things happen under the covers:

MyClass c=new MyClass();

Memory is allocated, the constructor is called, and the memory location is assigned to the variable c. The JVM is allowed to reorder those actions. This causes problems if memory is allocated, the value is assigned, and a thread interrupts and uses the value before the constructor is called.

volatile MyClass c=new MyClass();

Under the 1.5 rules, the assignment is guaranteed to be the last one of those events. The "side effects" are the allocation and the constructor call.

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