Singleton on a multithreaded environment

Static keyword
Java itself facilitates creation of global single classes using a static key word. But using static classes in concurrency is a disadvantage. When a class is declared as static both class and instance methods use the same object lock. This may lead to deadlocks and competition to acquire a lock. Also static fields instantiate at the state of class loading. This mean static may lead to start-up overheads. Singleton classes guarantee only one instance over the program. Singleton also has several variants. Most of these mechanisms guarantee a single instance in sequence programming which is when only one thread is running, but in concurrent programming it is guaranteed to have multiple threads accessing same singleton class. Singleton can be destined to keep predefined instances over program.

class BarMaid {
 private BarMaid() {
 }
 private static BarMaid uniqueinstance = null;
 public synchronized static BarMaid getuniqueinstance()
 {
   if (uniqueinstance == null)
   uniqueinstance = new BarMaid();
   return uniqueinstance;
  }
}
Above code shows singleton approach to BarMaid class. But when multiple threads access the class at same time it returns multiple instances.


Lazy Instantiation

A singleton can be designed to avoid situations like above by avoiding lazy instantiation. JVM loads class dynamically. Quality of static keyword is that it executes first and does not internalize until the class load happens dynamically. This will guarantee thread safety of the singleton.
    public class LandLord{
    LandLord();
    private static LandLord uniqueinstance = new private LandLord() {}
      public static LandLord getuniqueinstance() {
      return uniqueinstance;
      }
    }

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.