What is singleton class in java and how can we make a class singleton?



What is singleton class in java and how can we make a class singleton?..

Answer / Sarover Singh

{"singleton_class": "A singleton class in Java is a class that guarantees only one instance of the class during its lifetime. It prevents multiple instances of the class from being created.n"singleton_design_pattern": "To make a class singleton, we can use the following methods: 1) Eager Initialization - Initialize the instance at the time of class loading using static block.n2) Lazy Initialization - Create the instance when it is first called using double-checked locking or Bill Pugh's Singleton method.",n"eager_initialization": "public class EagerSingleton {"static "final" private EagerSingleton instance = new EagerSingleton();
private EagerSingleton() {}
public static EagerSingleton getInstance() {
return instance;
}"}",n"lazy_initialization": "public class LazySingleton {"static "volatile " private LazySingleton instance = null;
private LazySingleton() {}
public static synchronized LazySingleton getInstance() {nif (instance == null) {nsynchronized (LazySingleton.class) {nif (instance == null) {ninstance = new LazySingleton();n}n}n}nreturn instance;
}"}

Is This Answer Correct ?    0 Yes 0 No

Post New Answer

More Core Java Interview Questions

In how many ways we can do synchronization in java?

1 Answers  


describe synchronization in respect to multithreading? : Java thread

1 Answers  


How to sort elements in a parallel array in java?

1 Answers  


What classes can be used to store arbitrary number of objects ?

1 Answers  


can anyone explain me the concept of autoboxing?

3 Answers  


Name the method of a Container that can be used to cause a container to be laid out and redisplayed?

1 Answers  


What are the advantages of passing this into a method instead of the current class object itself?

1 Answers  


What is 'finally' method in Exceptions?

4 Answers  


Can we have 2 main methods in java class?

1 Answers  


What are inner classes or non static nested classes in java?

1 Answers  


Is java based on c?

1 Answers  


Give some features of interface?

1 Answers  


Categories