Jan 28, 2014

Creating Singleton class

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
   }
}


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;
}


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;
}


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;
}


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;
  }

}



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.

Jan 25, 2014

Synchronization on static method and instance method

Before getting into synchronization concept, lets first understand what is monitor. 

A monitor is a kind of lock that each class owns. And that monitor, at any time can be held only by a single Thread. When a class is instantiated, each instance is allocated with one monitor. 

Consider our class is Student.java 

public class Student{

 public void getStudentName(){
   //Code
 }

  synchronized(this){
     //code
  }
}

When some thread tries to execute the synchronized method/block, first the thread acquires the monitor that belongs to that instance so that the monitor is not available for any other thread of same instance till this thread completes its task and releases the monitor. The monitor could also be released by putting the thread into wait() status. Note here, if a thread acquires the monitor of an instance, then any synchronized block in that instance cannot be accessed by any thread. But anyhow, non synchronized block is still available for access. 

Threads of other instances have access to this synchronized block as each object has its own monitor.


Static synchronized block:
If our Student class has a static synchronized block & any thread try to access this block,  the monitor belongs to the class itself is acquired by the thread that executes the static block. So any thread on any other instances of this class has to wait till this monitor is released. So be cautious while you develop a static synchronized method.

static Synchronized block is given below.

public static synchronized void getStudentDetails(){
   //Code here
}


A class level lock can be made even by following way. They both have similar effect.

public static void getStudentDetails(){
  synchronized(Student.class){
    //Code here
  }

  

Java Thread: Why do we always call start() method, not run() method in thread


We can see both public void run() and public synchronized void start() are methods of Thread class but we always use thread.start() to invoke the thread rather than using thread.run(). Why? The reason is explained below.

When we invoke a thread using start() method, a new thread stack is created and the run() method starts executing in a new thread stack. But if we call the run() method directly, the new thread stack is not created, rather the run() method executes in current thread stack. The following example clearly tells the difference between calling start() & run() methods.

MyThreadClass.java

public class MyThreadClass implements Runnable {

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+" is running.");
    }
}

MainClass.java

public class MainClass {

   public static void main(String[] args) {
        Thread.currentThread().setName("Main Thread");
        System.out.println("This is main thread: "+Thread.currentThread().getName());
      
        MyThreadClass myThread = new MyThreadClass();
        Thread t = new Thread(myThread, "My Thread");
        t.start();
    }
}

Output:

This is main thread: Main Thread //This is instance of main thread.
My Thread is running. //This is new thread instance.


If we call run() method directly, we can clearly see that the output changes as follows:


Output:

This is main thread: Main Thread //This is instance of main thread.
Main Thread is running. //run() is also invoked in main thread stack.