创建 volatile 类是否保证 volatile 类变量

发布于 2024-10-20 23:01:45 字数 647 浏览 8 评论 0原文

假设以下单例:

public class Test{
    private static volatile Test test = null;
    private static int test_int = 0;
    private static String test_string = "test";

    public int getInt(){
       return test_int;
    }

    public String getString(){
        return test_string;
    }

    private static Test getInstance(){
         if(test == null){
             synchronized(Test.class){
                if(test == null)
                    test = new Test();
             }
         }
    }

通过将单例实例 Test 声明为易失性, test_int 和 test_string 也被视为易失性,还是必须如此声明?我想认为,通过使类本身成为易失性的,那么该类下的所有内容也将是易失性的......但是我对此不确定。提前致谢。

Suppose the following singleton:

public class Test{
    private static volatile Test test = null;
    private static int test_int = 0;
    private static String test_string = "test";

    public int getInt(){
       return test_int;
    }

    public String getString(){
        return test_string;
    }

    private static Test getInstance(){
         if(test == null){
             synchronized(Test.class){
                if(test == null)
                    test = new Test();
             }
         }
    }

By declaring the singleton instance Test to be volatile are test_int and test_string also considered to be volatile or must they be declared as such? I want to think that by making the class itself Volatile then everything under that class would be volatile as well ... however I am not sure about this. Thanks ahead of time.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你的呼吸 2024-10-27 23:01:45

不,它们不被认为是不稳定的。 只有 test 变量是易失性的。在获得 test 的值(通过 getInstance)后,其波动性与客户端的其余行为无关。

老实说,我个人会考虑使用 AtomicIntegerAtomicReference 而不是 volatile。我不了解其他人,但我发现不稳定的行为很难可靠地推理。

请注意,您可能不希望您的 test_inttest_string 变量是静态的......

No, they aren't considered to be volatile. Only the test variable is volatile. After the value of test has been obtained (via getInstance) its volatility is irrelevant to the rest of the client's behaviour.

Personally I would consider using AtomicInteger and AtomicReference instead of volatile, to be honest. I don't know about anyone else, but I find volatile behaviour hard to reason about reliably.

Note that your probably don't want your test_int and test_string variables to be static...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文