First let us understand what is singleton pattern.
Singleton pattern is a design pattern that restricts the instantiation of a class to one object. i.e. You can create only one instance for that class and no more instance can be created. So whenever you request for an instance of that class, same instance which ever created initially is retrieved. One best example of singleton class is Logger class.
Now the question is, how to create a singleton class. Of course, there are lot of ways to create such class. Now let's see one of those methods.
1. First of all, you shouldn't allow anyone to create a new instance, i.e. the creation of instance should be restricted to any external entity. Your class should take care of creating instance for this class.
First restriction is to put on constructor level. i.e. Make your constructor as private. So any other class will not have access to this class' constructor.
class MyLogger{
private MyLogger(){
//Code
}
}
private MyLogger(){
//Code
}
}
2. If you cannot create an instance, then how will you get the instance of this class and how will you access other methods in this class.
So we have to look for other options to access this class. We all know that static methods of a class can be accessed without it's instance. i.e. We can access all static methods using ClassName itself.
Now create a public static method that retrieves the instance for this particular class when ever some one requests for an instance.
Use a private static variable to store the class instance as following,
private static MyLogger logger = null;
//Static method (make sure your method is public,
//so it can be accessed from other classes)
public static MyLogger getInstance(){
if(logger == null){ //logger is null only for first time.
logger = new MyLogger();
}
return logger;
}
//Static method (make sure your method is public,
//so it can be accessed from other classes)
public static MyLogger getInstance(){
if(logger == null){ //logger is null only for first time.
logger = new MyLogger();
}
return logger;
}
Here we can see the static method getInstance() checks for instance & creates a new one if there is no existing instance available. If it finds an existing instance, it just returns the same.
But if we take a closer look, this method doesn't seem to be thread safe. How? Consider there are no instance created for this class. Two new threads executes this method to create instance at the same time. Say, thread1 enters into if(logger==null) condition & before it creates the instance, thread2 also checks the "if" condition. The condition is true and this thread (thread2) too enters into the "if" block. Now these 2 threads are inside the "if" block & now imagine what happens. Yes, you are right. 2 instances of MyLogger is created, which violates the singleton rule.
How can we handle this? Let's keep the instance creation part into synchronized block as given below, so multi thread access is restricted at same time.
public static MyLogger getInstance(){
if(logger == null){
synchronized(MyLogger.class){
logger = new MyLogger();
}
}
return logger;
}
if(logger == null){
synchronized(MyLogger.class){
logger = new MyLogger();
}
}
return logger;
}
Does this modification resolve the multiple-instance-creation issue? Nope. Why? Think if thread1 & thread2 both are into "if" block. Now thread1 enters into synchronized block, acquires the monitor, locks the class & creates the instance. thread2 waits till thread1 releases the monitor & as it is already inside "if" block, it now enters into synchronized block and creates another instance. How can we handle this?
We have a concept called double-checked-locking, where the check happens before synchronized block & inside synchronized block as given below.
public static MyLogger getInstance(){
if(logger == null){
synchronized(MyLogger.class){
if(logger == null){
logger = new MyLogger();
}
}
}
return logger;
}
if(logger == null){
synchronized(MyLogger.class){
if(logger == null){
logger = new MyLogger();
}
}
}
return logger;
}
Does it solve the issue? Of course yes. Only the thread that enters first creates the instance & rest of the threads get the already-created instance.
We can get a question here. Why can't we synchronize the whole method itself, while the synchronized block we mentioned above also locks the class anyway?
It can be done, but if we take a closer look, we can note that the synchronized static method always locks the class (Refer this link) whenever some class requests an instance, which means, the class is locked whenever an instance is requested. But with the double-checked-locking mechanism, the class is locked only once during first instance creation & rest of the calls won't go through the synchronized block.
We can also have other way of creating singleton class as given below.
class MyLogger {
private static MyLogger logger = new MyLogger();
private MyLogger(){ }
public static MyLogger getInstance(){
return logger;
}
}
private static MyLogger logger = new MyLogger();
private MyLogger(){ }
public static MyLogger getInstance(){
return logger;
}
}
This one is called eager loading, where static blocks will be loaded during class load itself. i.e. even before the request for an instance is arrived.
But our previous example creates instance only when some class requests for it. This one is called Lazy loading. Anyhow, both ways of creating singleton class serves its purpose.
No comments:
Post a Comment