Java:当使用锁时,所有可变变量是否需要是volatile? [英] Java: Do all mutable variables need to be volatile when using locks?

查看:203
本文介绍了Java:当使用锁时,所有可变变量是否需要是volatile?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下变量x是否需要是易失性的?

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

或者在utils.concurrent锁中的操作与同步块的功能相同(确保它被写入内存,而不是存储在cpu缓存中)?



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


推荐答案

如果他们在没有锁的情况下访问其他地方,则是易失的。例如,作为对大小变量的快速只读访问。锁定方法的作用与同步块相同。请参阅javadoc中锁定类。

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.

这篇关于Java:当使用锁时,所有可变变量是否需要是volatile?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆