Write a Singleton without using Synchronized keyword

7 views
Skip to first unread message

Rohit Ghatol

unread,
Dec 6, 2007, 6:19:58 AM12/6/07
to Pune Java Interview Questions Group
Write a Singleton class without using Synchronized keyword also take
care that you only create the singleton object when required.

Undertaker

unread,
Dec 6, 2007, 7:02:21 AM12/6/07
to Pune Java Interview Questions Group
public class MySingleTon
{
private static MySingleTon instance;

private MySingleTon() {
}

public static MySingleTon getInstance() {
if (instance == null)
instance = new MySingleTon();
return instance;

Rohit Ghatol

unread,
Dec 6, 2007, 9:58:54 AM12/6/07
to Pune Java Interview Questions Group
Nopes not exactly, see the following condition

See you still have to handle race condition when two thread get inside
getInstance method, one godes instance=new MySingleton() and as this
is happening, another thread has reached inside the if loop.
You will have two instances instead of one.

Think again!! Hint is you have to use JVM implicit class loading in
context of static variables.

Yogesh Patel

unread,
Dec 10, 2007, 2:01:59 AM12/10/07
to pune-java-intervi...@googlegroups.com
Hi All,

 Probably answer is:-

 public class SingleT {
         private static SingleT obj;
         static{
                         obj = new SingleT ();
         }
        public static SingleT  getSingleT (){
                 return obj;
       }
}



But the problem of above implementation is Whenever you use class SingleT  for any reason, it will create object. So as Rohit mentioned , even if you are not calling getSingleT (), it will create the object when JVM load class.



Yogesh//

Rohit Ghatol

unread,
Dec 10, 2007, 2:49:17 AM12/10/07
to pune-java-intervi...@googlegroups.com
public class Singleton{

   /**
    * Private constructor
    */
   private Singleton(){
   }
  
   /**
    * private static class, which only gets loaded when method getInstance() is invoked.
    */
   private static class SingletonHolder{
       /**
        * In this class initialize statically the instance of the Singleton Class.
        */
       public final static Singleton instance=new Singleton();
   }

   /**
    * The actual singleton getInstance method.
    * Only when you call this method the first time
    * the inner static class SingletonHolder gets initialized
    * Hence this is singleton
    */
   public static Singleton getInstance(){
       return SingletonHolder.instance;
   }
}

Just my 50 cents!!
Rohit
Reply all
Reply to author
Forward
0 new messages