具有易变变量的延迟初始化Singleton类 [英] Lazy initialization Singleton class with volatile variable

查看:63
本文介绍了具有易变变量的延迟初始化Singleton类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个单例类{惰性初始化}。代码如下所示。

I came across a singleton class {lazy initialization}. The code is as below

// Singleton reference for this class
    private static volatile FileProperties INSTANCE = null; 

    public static FileProperties getInstance() {
            if (INSTANCE == null) {
                synchronized (FileProperties.class) {
                    if (INSTANCE == null) {
                        INSTANCE = new FileProperties();
                    }
                }
            }
            return INSTANCE;
        }

我的问题是,通过 INSTANCE获得什么好处?易失性
,因为我们已经通过同步处理了线程安全性。
在这种情况下,volatile有什么好处吗?

My question is what is the benefit we are getting by making INSTANCE as volatile Since we already taking care of thread safety by synchronized. Is there any benefit of volatile in this scenario ?

推荐答案

这是因为在没有<$ c的情况下进行了双重检查锁定$ c> volatile 在Java中不是线程安全的。

That is because double-checked locking without volatile is not thread-safe in Java.

使线程安全的lazy-init单例的最简单方法是创建类持有人,如下所示:

The simplest way to make thread-safe lazy-init singleton is to create class holder as follows:

public class SomeClass {
    private static class SomeClassHolder {
        public static final SomeClass INSTANCE = new SomeClass();
    }

    public static SomeClass getInstance() {
       return SomeClassHolder.INSTANCE;
    } 

    private SomeClass() {}

}

由于JVM行为,该部分代码将加载SomeClassHolder并在第一次使用 getInstance()时创建SomeClass的实例(而不是在SomeClass时)

That part of code, because of JVM behavior will load SomeClassHolder and create an instance of SomeClass on first usage of getInstance() (and not when SomeClass is loaded by classloader).

您根本不需要使用任何同步!!因为JVM正在为您完成。

You don't need to use any synchronization at all!! Because JVM is doing it for you.

这篇关于具有易变变量的延迟初始化Singleton类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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