Below are two ways to implement a singleton. What are the advantages and disadvantages of each?
Static initialization:
class Singleton {
private Singleton instance;
static {
instance = new Singleton();
}
public Singleton getInstance() {
return instance;
}
}
Lazy initialization is:
class Singleton {
private Singleton instance;
public Singleton getInstance(){
if (instance == null) instance = new Singleton();
return instance;
}
}
First one is eager initialisation.
eager initialization creates the instance even before it’s being used and that is not the best practice to use.
Second one is Lazy Initialization.
Lazy implementation works fine incase of single threaded environment but when it comes to multithreaded systems, it can cause issues if multiple threads are inside the if loop at the same time. It will destroy the singleton pattern and both threads will get the different instances of singleton class.
Please visit: http://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-with-examples#static-block-initialization for more information
NOTE: static blocks can access only static variables defined outside static block directly. The object you want to restrict to only one instance creation should be static. Your first methods fails during compilation, second method requires you to create the object first
Follow this approach:
class Singleton
{
private static Singleton instance;
private Singleton()
{
}
public static Singleton getInstance()
{
if(instance == null)
instance = new Singleton();
return instance;
}
}
Ensure no creation of the object elsewhere, so change the constructor to private
make your class like this
public class Singleton {
private Singleton() {
}
private static Singleton instance;
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
and call it like..
Singleton instance = Singleton.getInstance();
Static initializers cannot throw exceptions and absorb RuntimeExceptions into ClassDefNotFoundException, which does not halt execution. So you could see lots of
ClassDefNotFoundException's in your logs and you might not even realize something is wrong until much later because execution continues.
The 2nd method allows RuntimeExceptions to stop execution.
More details here:
https://twasink.net/2006/07/07/how-not-to-handle-exceptions-from-static-code-block-in-java/