Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 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

question from:https://stackoverflow.com/questions/65598496/will-atomicreference-cause-my-lazy-instance-to-wrongly-be-created-at-application

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

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...