Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

java - Will AtomicReference cause my lazy instance to wrongly be created at application launch?

I need to sanity check my lazy implementation of a singleton. 'Wrongly' in the title refers to my requirements

It's a common pattern to use what I know as a Bill Pugh singleton so that the Instance is not created unless it is actually used (because the static inner class is not loaded into memory until the getInstance() method is called). Example:

MyBillPughSingleton {

    private MyBillPughSingleton () { ... }

    public MyBillPughSingleton getInstance() {
        return MySingletonHolder.INSTANCE;
    }

    static class MySingletonHolder {
        static final MyBillPughSingleton INSTANCE = new MyBillPughSingleton();
    }

}

I have a case where my singleton needs a callback for initialization, so I considered the following approach. Does this still maintain the advantage of not being loaded into memory immediately?

MySingleton {

    private MySingleton (MyParam myParam) { ... }

    public MySingleton getInstance(MyParam myParam) {
        if (MySingletonHolder.INSTANCE.get() == null) {
            MySingletonHolder.INSTANCE.set(new MySingleton(myParam));
        }    
        return MySingletonHolder.INSTANCE.get();
    }

    static class MySingletonHolder {
        static final AtomicReference<MySingleton> INSTANCE = new AtomicReference<>();
    }

}

This will be lazily accessed via Dependency Injection in an Android application, I am not aware of any specific memory model differences which would affect this for Android differently than in other Java apps, but I mention it in case you know of such. The param once created will always be the same, but that should not be important since since it will only be used the first time


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...