开发者

Java: Do all mutable variables need to be volatile when using locks?

开发者 https://www.devze.com 2023-01-12 15:27 出处:网络
Does the following variable, x, need to be volatile? Or does the manipulation within a utils.concurrent lock perform the same function as a synchronized block (ensuring it\'s written to memory, and

Does the following variable, x, need to be volatile?

Or does the manipulation within a utils.concurrent lock perform the same function as a synchronized block (ensuring it's written to memory, and not stored in cpu cache)?

myMethod(){
  myLock.lock();
  x++;
  myLock开发者_高级运维.unlock();
}


Such variables only need to be volatile if they're accessed elsewhere without a lock. For example, as a fast read-only access to a size variable. The lock methods do serve the same purpose as a synchronized block. See the "Memory Synchronization" section in the javadoc for the Lock class.

0

精彩评论

暂无评论...
验证码 换一张
取 消