2

I have gone through a singleton design pattern in Java which is below mentioned. I am having trouble to understand how does the Synchronized keyword in the public static getter or accessor method prevent more than one object creation ? If at all it is being called twice from two different classes Synchronized should make their calls Synchronized i.e. one after the other . How does it govern only one object creation? Please explain in details and also check the comments if my assumptions about the modifiers are correct or not

class MySingleton
{
private static MySingleton singletonObj; //as it is private it cannot be referenced outside of this class
                                         //and as it is static all the instances of this class share the same copy of this refrence variable
private MySingleton()
{
    System.out.println("Welcome to a singleton design pattern");
    System.out.println("Objects cannot be instantiated outside of this class"); 
}

public static synchronized MySingleton getASingletonObject()
{
    if(singletonObj==null)
    {
        singletonObj=new MySingleton();
    }
    return singletonObj;
}


}

Help is much appreciated :) Thanks

StrugglingCoder
  • 4,781
  • 16
  • 69
  • 103
  • 4
    And you seriously didn't think about googling it ? There are a few ways to implement a singleton in Java: 1. like you did. 2. double check pattern with instance declared as volatile. 3. using Enum. 4. Using inner class for lazy instantiation. and maybe others. BTW, the convention is to name the method `getInstance()` – Nir Alfasi Jun 05 '14 at 07:39
  • 1
    Check this http://www.javaworld.com/article/2073352/core-java/simply-singleton.html – Rohan Jun 05 '14 at 07:41
  • See [Thread Safe singleton class](http://stackoverflow.com/a/16106598/256196) – Bohemian Jun 05 '14 at 07:48
  • Josh Bloch's Effective Java contains a nice write up on this topic. Surely some googling will give you a link to a presentation or some video recorded material. – rethab Jun 05 '14 at 07:49

5 Answers5

3

Your question is about the way it works: You have one instance not because of the synchronized, but because it is stored in a static variable, and is instancied only one time (with a lazy creation - checked by the if).

The synchronized ensure you that only one Thread will instanciate the object, and avoid a bug where many Threads could create duplicates.

Here is the other way to implement it, and i find it more simple, and as efficient:

public class Singleton
  private static final Singleton instance=new Singleton();
  private Singleton(){
  }
  public static Singleton getInstance(){
    return instance;
  }
}

Note: the only condition for using this kind of implementation is that your constructor (the new) should not throw any exception, and should only contain simple code like variable initialisation.

Community
  • 1
  • 1
pdem
  • 3,880
  • 1
  • 24
  • 38
  • The alternative for synchronized mentioned by you is very useful. It is definitely more efficient than synchronized, esp in scenarios where singleton is used commonly in the program. That outweighs lazy initialization benefit. – garnet Dec 24 '15 at 06:48
  • 1
    @Adil Aliyev It is only initialized when we reference it, The classloader won't load the class thus don't initiliaze it "unnecessarily". So if we only used Singleton.getInstance() in our code, it just work the same way as the "synchronized one" – pdem Nov 16 '16 at 13:24
  • Additionnaly it has been proven, that for so many years, java developper did wrong by using a double synchronization : http://www.javaworld.com/article/2074979/java-concurrency/double-checked-locking--clever--but-broken.html Trying to be clever is not always good, in this case, just be simple is more efficient. – pdem Nov 16 '16 at 13:28
2

You´re not implementing correctly Singleton patter look my implementation.

     class MySingleton
     {

     private MySingleton instance; //You dont need that you instance be static, inside your class you have all the access of the Instance once you call getInstance()

     public static MySingleton getInstance(){
              return instance;
     }


     private MySingleton() 
     {   
         System.out.println("Welcome to a singleton design pattern");
         System.out.println("Objects cannot be instantiated outside of this class"); 
     }

     public static synchronized MySingleton getASingletonObject()
     {
         if(instance==null)
         {
             instance=new MySingleton();
         }
         return instance;
     }

 }

//About the synchronized you have to understand that is like a lock, where every time a thread is getting inside he is closing the method so nobody else can be inside and then there´s no possible that when a thread is in the line instance=new MySingleton(); but has not being executed for the VM another thread would be in if(instance==null) asking the VM and returning true. As soon as the first tread is out of the method the lock is open and then other threads can get in. And then they will see that the instance is already created.

pdem
  • 3,880
  • 1
  • 24
  • 38
paul
  • 12,873
  • 23
  • 91
  • 153
2

The purpose of the Singleton class is that there is at most one instance of it and, hence, all threads access that same object. Supposing there are 'n' threads trying to access the getASingletonObject method.

Case I:If we don't synchronize the getASingletonObject method the following could happen:

1) Thread1 enters getASingletonObject()

2) Thread2 enters getASingletonObject()

3) Thread1 evaluates singletonObj == null to true

4) Thread2 evaluates singletonObj == null to true

5) Thread1 assigns singletonObj and returns

6) Thread2 *re*assigns singletonObj = new Singleton() and returns.

Now the threads both have a difference instance of the Singleton class which is what should have been prevented by this pattern.

Synchronizing prevents that both Threads can access the same block of code at the same time. So synchronization is needed in a multithreaded environment when you instantiate singleton classes.

Now assuming that multple threads will attempt to access the Singletons methods at the same time synchronization might be neccessary on those methods as well. Especially if they change data instead of only reading it this is true.

Manitude
  • 100
  • 7
1

The synchronized keyword protects the singleton member variable (singletonObj in this case) from multithreaded access. This ensures that even if multiple threads are trying to create an object, only one is still being used.

Check this article: http://www.javaworld.com/article/2073352/core-java/simply-singleton.html for more explanation.

ufuoma
  • 237
  • 1
  • 7
0

Wikipedia says:

In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object.

So you create singletonObj only one-time because when you call getASingletonObject() you check is singletonObj == null and if it's null, so you create a new object, if it's not null you get 'singletonObj' created before.

public static synchronized gives you confidence that this object have been created once, because static says that singletonObj have been created once for class, but not for concrete instance of object. And synchronized provides a concurrent access to getASingletonObject() and it's give you confidence that object singletonObj couldn't be created twice when different threads call your method simultaneously.

Aleksandr Podkutin
  • 2,532
  • 1
  • 20
  • 31