What is the best way to create a singleton class in java? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What is the best way to create a singleton class in java?

What is the best way to create a singleton class in java?

7th Oct 2017, 1:22 AM
Adarsh Srivastava
Adarsh Srivastava - avatar
4 Answers
+ 3
Here are a few of the singleton design pattern constructs. As to which is best, it depends on how you're using it and is otherwise subjective. // Lazy Initialization public class Singleton { private static Singleton instance = null; private Singleton() {} public static Singleton getInstance() { if(instance == null) { instance = new Singleton(); } return instance; } } // Thread safe public class Singleton { private static Singleton instance; private Singleton() {} public static synchronized Singleton getInstance() { if(instance == null) { instance = new Singleton(); } return instance; } } //Thread safe with locking public class Singleton { private static Singleton instance; private Singleton() {} public static Singleton getInstance() { if(instance == null) { synchronized (Singleton.class) { if(instance == null) { instance = new Singleton(); } } } return instance; } } // Helper class "Bill Pugh" public class Singleton { private Singleton() {} private static class SingletonHelper { private static final Singleton INSTANCE = new Singleton2(); } public static Singleton getInstance() { return SingletonHelper.INSTANCE; } } // Eager Initialization public class Singleton { private static final Singleton INSTANCE = new Singleton(); private Singleton() {} public static Singleton getInstance() { return INSTANCE; } } // Static Block public class Singleton { private static Singleton instance; private Singleton() {} static { instance = new Sigleton(); } public static Singleton getInstance() { return instance; } }
7th Oct 2017, 2:54 AM
ChaoticDawg
ChaoticDawg - avatar
+ 1
i asked for creation of a singleton
7th Oct 2017, 2:18 AM
Adarsh Srivastava
Adarsh Srivastava - avatar
0
Google Design Patterns for Java.
7th Oct 2017, 1:36 AM
Freezemage
Freezemage - avatar