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

余生颓废 提交于 2020-01-14 13:51:30

问题


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();
}

回答1:


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.



来源:https://stackoverflow.com/questions/3552956/java-do-all-mutable-variables-need-to-be-volatile-when-using-locks

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