gpt4 book ai didi

java - volatile 和 synchronized 在一起

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:19:57 24 4
gpt4 key购买 nike

是否有任何理由在此代码中同时使用 volatile 和 synchronized?

public class Helper {
private volatile int n;
private final Object lock = new Object();
public Helper(int n) {
this.n = n;
}

public void setN(int value) {
synchronized (lock) {
n = value;
}
}
}

类助手必须是线程安全的。我从《Java Concurrency Guidelines》一书中得到了这个例子,但还是不清楚:这个例子中为什么要同时使用volatile和synchronized?

最佳答案

这个例子的目的是指出syncronized没有volatile在这种情况下是不够的,因为对象可以不安全地发布(即 volatile 中没有 Foo):

If the helper field in the Foo class is not declared volatile, the n field should be declared volatile so that a happens-before relationship is established between the initialization of n and the write of Helper to the helper field. This is in compliance with guideline “VNA06-J. Do not assume that declaring an object reference volatile guarantees visibility of its members” on page 35. This is required only when the caller (class Foo) cannot be trusted to declare helper volatile.

这是正确的,但他们选择了一个不好的例子来证明它,因为volatile在这种情况下,无需同步就足够了。

关于java - volatile 和 synchronized 在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10122907/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com