Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Thread safe singleton that take parameters for instantiation

826367Jan 27 2011 — edited Jan 30 2011
Hi,

I understand the following class is an example of thread safe implementation of Singleton.

This class initializes the instance lazily and in a thread safe manner. The drawback being that parameters cannot be passed into the getInstance method to construct the instance.

Can someone please guide me on how to achieve (1) Thread safe singleton and (2) Lazy initialization of the instance and (3) Parameterizing the getInstance method.

I've tried searching on the web for some guidance on this... All that I can find are either "DCL is broken" or the following implementation.

Thank you.
public class Singleton {
    private Singleton() {}
    
    public static Singleton getInstance() {
        return SingletonHolder.getInstance();
    }
    
    private static class SingletonHolder {
        private static Singleton s_instance;
        static {
            s_instance = new Singleton();
        }
        
        public static Singleton getInstance() {
            return s_instance;
        }
    }
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Feb 27 2011
Added on Jan 27 2011
21 comments
7,418 views