Java Singleton and Synchronization

Please clarify my queries regarding Singleton and Multithreading:

  • What is the best way to implement Singleton in Java, in a multithreaded environment?
  • What happens when multiple threads try to access getInstance() method at the same time?
  • Can we make singleton's getInstance() synchronized?
  • Is synchronization really needed, when using Singleton classes?

Yes, it is necessary. There are several methods you can use to achieve thread safety with lazy initialization:

Draconian synchronization:

private static YourObject instance;

public static synchronized YourObject getInstance() {
    if (instance == null) {
        instance = new YourObject();
    }
    return instance;
}

This solution requires that every thread be synchronized when in reality only the first few need to be.

Double check synchronization:

private static final Object lock = new Object();
private static volatile YourObject instance;

public static YourObject getInstance() {
    YourObject r = instance;
    if (r == null) {
        synchronized (lock) {    // While we were waiting for the lock, another 
            r = instance;        // thread may have instantiated the object.
            if (r == null) {  
                r = new YourObject();
                instance = r;
            }
        }
    }
    return r;
}

This solution ensures that only the first few threads that try to acquire your singleton have to go through the process of acquiring the lock.

Initialization on Demand:

private static class InstanceHolder {
    private static final YourObject instance = new YourObject();
}

public static YourObject getInstance() {
    return InstanceHolder.instance;
}

This solution takes advantage of the Java memory model's guarantees about class initialization to ensure thread safety. Each class can only be loaded once, and it will only be loaded when it is needed. That means that the first time getInstance is called, InstanceHolder will be loaded and instance will be created, and since this is controlled by ClassLoaders, no additional synchronization is necessary.

Java Singleton and Synchronization, Yes, it is necessary. There are several methods you can use to achieve thread safety with lazy initialization: Draconian synchronization: Can we make singleton's getInstance() synchronized? Is synchronization really needed, when using Singleton classes? Not required if you implement the Singleton in below ways. static intitalization; enum ; LazyInitalaization with Initialization-on-demand_holder_idiom ; Refer to this question fore more details. Java Singleton Design Pattern

This pattern does a thread-safe lazy-initialization of the instance without explicit synchronization!

public class MySingleton {

     private static class Loader {
         static final MySingleton INSTANCE = new MySingleton();
     }

     private MySingleton () {}

     public static MySingleton getInstance() {
         return Loader.INSTANCE;
     }
}

It works because it uses the class loader to do all the synchronization for you for free: The class MySingleton.Loader is first accessed inside the getInstance() method, so the Loader class loads when getInstance() is called for the first time. Further, the class loader guarantees that all static initialization is complete before you get access to the class - that's what gives you thread-safety.

It's like magic.

It's actually very similar to the enum pattern of Jhurtado, but I find the enum pattern an abuse of the enum concept (although it does work)

Thread Safety in Java Singleton Classes, Create the instance variable at the time of class loading. � Synchronize the getInstance() method. � Use synchronized block inside the if loop and volatile variable. Can we make singleton’s getInstance() synchronized? Is synchronization really needed, when using Singleton classes? Not required if you implement the Singleton in below ways. static intitalization; enum ; LazyInitalaization with Initialization-on-demand_holder_idiom ; Refer to this question fore more details. Java Singleton Design Pattern

If you are working on a multithreaded environment in Java and need to gurantee all those threads are accessing a single instance of a class you can use an Enum. This will have the added advantage of helping you handle serialization.

public enum Singleton {
    SINGLE;
    public void myMethod(){  
    }
}

and then just have your threads use your instance like:

Singleton.SINGLE.myMethod();

Java Singleton Design Pattern Example Best Practices, In this approach, the synchronized block is used inside the if condition with an additional check to ensure that only one instance of a singleton class is created. The� On the other hand, synchronized will cause all modifications guarded by the considered lock to synchronize with main memory (visibility feature) and adds mutual exclusion; this prevents an object

Yes, you need to make getInstance() synchronized. If it's not there might arise a situation where multiple instances of the class can be made.

Consider the case where you have two threads that call getInstance() at the same time. Now imagine T1 executes just past the instance == null check, and then T2 runs. At this point in time the instance is not created or set, so T2 will pass the check and create the instance. Now imagine that execution switches back to T1. Now the singleton is created, but T1 has already done the check! It will proceed to make the object again! Making getInstance() synchronized prevents this problem.

There a few ways to make singletons thread-safe, but making getInstance() synchronized is probably the simplest.

Double-Checked Locking with Singleton, public static synchronized DraconianSingleton getInstance() { In fact, the Java memory model allows the publication of partially initialized� Using synchronized we can create singleton class in multi-threading environment also but it can cause slow performance, so we can use Double check locking mechanism. Bill Pugh implementation is most widely used approach for singleton classes. Most developers prefer it because of its simplicity and advantages.

Enum singleton

The simplest way to implement a Singleton that is thread-safe is using an Enum

public enum SingletonEnum {
  INSTANCE;
  public void doSomething(){
    System.out.println("This is a singleton");
  }
}

This code works since the introduction of Enum in Java 1.5

Double checked locking

If you want to code a "classic" singleton that works in a multithreaded environment (starting from Java 1.5) you should use this one.

public class Singleton {

  private static volatile Singleton instance = null;

  private Singleton() {
  }

  public static Singleton getInstance() {
    if (instance == null) {
      synchronized (Singleton.class){
        if (instance == null) {
          instance = new Singleton();
        }
      }
    }
    return instance ;
  }
}

This is not thread-safe before 1.5 because the implementation of the volatile keyword was different.

Early loading Singleton (works even before Java 1.5)

This implementation instantiates the singleton when the class is loaded and provides thread safety.

public class Singleton {

  private static final Singleton instance = new Singleton();

  private Singleton() {
  }

  public static Singleton getInstance() {
    return instance;
  }

  public void doSomething(){
    System.out.println("This is a singleton");
  }

}

Singletons in Java, See how to implement the Singleton Design Pattern in plain Java. public synchronized static ClassSingleton getInstance() {. if (INSTANCE� The Singleton's purpose is to control object creation, limiting the number of objects to only one. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields. Singletons often control access to resources, such as database

Java Singleton Pattern and Synchronization, In this post we are going to see implementation of singleton pattern and how synchronization works particularly in this design pattern, also we� Singleton vs Synchronized. 1) Singleton restricts at class level while “synchronized” restricts access at method level only. 2) So, “synchronized” will have better performance than “singleton” since in case of synchronized. a.

How to make the perfect Singleton? | by Keval Patel, The Singleton is one of the Creational Design Patterns in Java. As you made your getInstance() class synchronized the second thread will have to wait until� You need synchronization inside getInstance only if you initialize your singleton lazily. If you could create an instance before the threads are started, you can drop synchronization in the getter, because the reference becomes immutable.

Thread-Safe and a Fast Singleton Implementation, Crunchify Singleton Pattern in Java. In software Simple Singleton Pattern: ( Lazy Initialization + ThreadSafe with synchronized block). Singleton singleton = Singleton.getInstance(obj); synchronized (singleton) { singleton.methodA(); singleton.methodB(); } Explanation: Is the 1. assumption correct because the synchronized on a not static method synchronizes on the object itself and since it is always the same object, the access is synchronized?

Comments
  • Warning - be careful with double-checked synchronization. It doesn't work properly with pre-Java 5 JVMs due to "issues" with the memory model.
  • -1 Draconian synchronization and Double check synchronization getInstance()-method must be static!
  • @PeterRader They don't need to be static, but it might make more sense if they were. Amended as requested.
  • You're implementation of double checked locking isn't guaranteed to work. It's actually explained in the article you cited for double checked locking. :) There is an example in there using volatile that works properly for 1.5 and higher (double checked locking is just plain broken below 1.5). The initialization on demand holder also cited in the article would probably be a simpler solution in your answer.
  • @MediumOne AFAIK, r is not needed for correctness. It's just an optimization to avoid accessing the volatile field, since that's far more expensive than accessing a local variable.
  • Synchronization is still present, it's just enforced by the JVM instead of by the programmer.
  • @Jeffrey You're right of course - I was typing it all in (see edits)
  • I understand it makes no difference to the JVM, I am just saying it made a difference to me as far as self-documented code goes. I've just never seen all caps in Java without the "final" keyword before (or enum), got a bit of cognitive dissonance. For someone programming Java full time, it probably would not make a difference, but if you jump languages back and forth, it helps to be explicit. Ditto for newbies. Although, I am sure one can adapt to this style pretty quick; all caps is probably enough. Don't mean to nit pick, I liked your post.
  • Excellent answer, though I didn't get some part of it. Can you elaborate "Further, the class loader guarantees that all static initialization is complete before you get access to the class - that's what gives you thread-safety." , how that helps in thread safety, I'm a little confused about that.
  • @wz366 actually, although it's not necessary, I agree for style reasons (since it is effectively final because no other code can access it) final should be added. Done.
  • Will it help by putting object creation code in Synchronized block, instead of making entire method synchronization?
  • @RaoG No. You want both the check and the creation in the synchronization block. You need those two operations happen together without interruptions or the situation I described above may happen.
  • @Vimsha A couple other things. 1. You should make instance final 2. You should make getInstance() static.
  • What would you do if you want to create a thread in the singleton.
  • @arun-george use a thread pool, a single thread pool if needed, and surround with a while(true)-try-catch-throwable if you want to ensure your thread never dies, no matter what error?