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 |
In how many ways we can do synchronization in java?
describe synchronization in respect to multithreading? : Java thread
How to sort elements in a parallel array in java?
What classes can be used to store arbitrary number of objects ?
can anyone explain me the concept of autoboxing?
Name the method of a Container that can be used to cause a container to be laid out and redisplayed?
What are the advantages of passing this into a method instead of the current class object itself?
What is 'finally' method in Exceptions?
Can we have 2 main methods in java class?
What are inner classes or non static nested classes in java?
Is java based on c?
Give some features of interface?