通过 ReentrantLock 访问的字段是否需要 volatile 关键字?
我的问题是,使用 ReentrantLock 是否可以保证字段的可见性,就像同步关键字提供的那样。
例如,在下面的类A中,字段sharedData不需要声明为易失性,因为使用了synchronized关键字。
class A
{
private double sharedData;
public synchronized void method()
{
double temp = sharedData;
temp *= 2.5;
sharedData = temp + 1;
}
}
然而,对于使用 ReentrantLock 的下一个示例,该字段上的 volatile 关键字是否必要?
class B
{
private final ReentrantLock lock = new ReentrantLock();
private volatile double sharedData;
public void method()
{
lock.lock();
try
{
double temp = sharedData;
temp *= 2.5;
sharedData = temp + 1;
}
finally
{
lock.unlock();
}
}
}
我知道无论如何使用 volatile 关键字只会对性能造成很小的影响,但我仍然想正确编码。
My question refers to whether or not the use of a ReentrantLock guarantees visibility of a field in the same respect that the synchronized keyword provides.
For example, in the following class A, the field sharedData does not need to be declared volatile as the synchronized keyword is used.
class A
{
private double sharedData;
public synchronized void method()
{
double temp = sharedData;
temp *= 2.5;
sharedData = temp + 1;
}
}
For next example using a ReentrantLock however, is the volatile keyword on the field necessary?
class B
{
private final ReentrantLock lock = new ReentrantLock();
private volatile double sharedData;
public void method()
{
lock.lock();
try
{
double temp = sharedData;
temp *= 2.5;
sharedData = temp + 1;
}
finally
{
lock.unlock();
}
}
}
I know that using the volatile keyword anyway will only likely impose a miniscule performance hit, but I would still like to code correctly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
安全无波动。
ReentrantLock
实现了Lock
,并且Lock
的文档包括:It's safe without volatility.
ReentrantLock
implementsLock
, and the docs forLock
include this: