SingleTon class is not synchronized and returning multiple instances

singleton class in java example with synchronized
singleton design pattern
use of singleton class in java
singleton with multiple instances
method of singleton class writes to a field in an unsynchronized manner
singleton without synchronized
when to use singleton design pattern in java
singleton design pattern interview questions

There is something wrong with my code below. I am getting multiple instances of the same singleton class when calling it from multiple threads from the same process. I am expecting the program should print "Creating instance" only once but it is printing 3 times(i.e. per thread).

package SingleTon;

class SingleTon implements Runnable {
    String name;
    int salary;
    private static SingleTon singleTonInstance;

    SingleTon() {

    }

    public static SingleTon getInstance() {
        if (singleTonInstance == null) {
            synchronized (SingleTon.class) {
                System.out.println("Creating instance");
                singleTonInstance = new SingleTon();
            }
        }
        return singleTonInstance;
    }

    @Override
    public void run() {
        System.out.format("Thread %s is starting\n",Thread.currentThread().getName());
        getInstance();
    }

}

package SingleTon;

public class SingleTonDemo {

    public static void main(String[] args) {
        System.out.println("test");
        SingleTon t = new SingleTon();
        Thread t1 = new Thread(t);
        Thread t2 = new Thread(t);
        Thread t3 = new Thread(t);
        t1.start();
        t2.start();
        t3.start();
    }

}

Output:

test
Thread Thread-0 is starting
Thread Thread-2 is starting
Thread Thread-1 is starting
Creating instance
Creating instance
Creating instance

You need to change the following:

1) Make your default constructor private. As written, it is package-private and can be called by other classes in the same package.

private SingleTon() {
}

Once you have done this, your SingleTonDemo class will no longer be able to call the constructor and will be forced to use the getInstance() method. Currently, each call to the constructor is creating a new instance.

2) Synchronize the entire getInstance() method. As written, 2 separate threads can get a null value for singleTonInstance, and thus each thread would create a new instance.

    public static SingleTon getInstance() {

2a) An alternate approach to ensuring there is only one instance of the class is to use static initialization. In the declaration of the static variable, you create the object:

private static SingleTon singleTonInstance = new SingleTon();

The JVM will ensure that this is called only one. That also improves your getInstance method as you would change it to:

public static SingleTon getInstance() {
    return singleTonInstance;
}

The advantage of this approach is that not only is the getInstance method simpler, it also does not incur the overhead of being synchronized.

When is a Singleton not a Singleton?, The Singleton can hold the number and synchronize access; if later you want to hold If you implement a factory class with a method that returns the Singleton instance, When copies of the Singleton class run in multiple VMs, an instance is� One of the common Singleton implementations uses lazy initialization of the one instance. That means that the instance is not created when the class loads, but rather when it is first used. (See Listing 2.) A common mistake with that implementation is to neglect synchronization, which can lead to multiple instances of the singleton class.

You are actually creating an instance of your SingleTon class outside of the class. This should not be done when using the singleton pattern, as only a single instance of the class should be able to be created.

For the synchronization issue:

If all three threads enter the if statement in your getInstance method, every thread will create an instance (as the if statement itself is not covered by the synchronized block). One way to solve this is to make the getInstance method synchronized, i.e. adding the synchronized modifier. In that case, the fetch-and-create-if-not-exists logic in your getInstance method is executed as an atomic block.

MSC07-J. Prevent multiple instantiations of singleton , Multiple instances of the Singleton class can be created when the getter method Not synchronized if (instance == null) { instance = new MySingleton(); } return� At line 43 & 46, we are deserializing & returning the instances of the SingletonSerial class. Now we have 3 instances of the Singleton class. After comparing them at line 49 & 50, we can see that they are all different showing that there are multiple instances of the Singleton class have been created.

public class SingleTonDemo {

public static void main(String[] args) {
    System.out.println("test");
    SingleTon t = SingleTon.getInstance();
    Thread t1 = new Thread(t);
    Thread t2 = new Thread(t);
    Thread t3 = new Thread(t);
    t1.start();
    t2.start();
    t3.start();
}

}

private SingleTon() {

}

Java Singleton Design Pattern Practices with Examples , Because instance of class is created always, whether it is required or not. An implementation of getInstance() method is required which return the instance. is made synchronized so that multiple threads can't access it simultaneously. synchronized (Singleton. class) {if we can create multiple objects in the Singleton class. Consider the following example: method in the Singleton class and return the same Singleton instance.

The Answer by EJK looks correct.

Here is an alternative, simpler approach entirely.

Enum

Generally speaking, the best way to implement a Singleton in Java is making an enum. The enum facility in Java is much more powerful and flexible than in most platforms; see Tutorial.

An enum in Java is actually a subclass of Enum, with the compiler/JVM handling that behind the curtains. When your enum class is loaded, the JVM automatically instantiates an object for each of your enum names. In the case of a singleton, of course, we have only one such enum name. Commonly this one name is INSTANCE but can be anything you desire.

Because an enum in Java is actually a class, you can define a constructor and pass objects to that constructor. In our example below, we pass an initial value for the name and salary members you used in your Question.

Similarly, as a class, an enum in Java can have methods. In our example below, we added a method run to implement Runnable, just as you did in your Question.

In the example here, we added a UUID value as an identifier as another way for you to see that indeed we have only a single instance of our singleton.

package work.basil.example;

import java.time.Instant;
import java.util.UUID;

public enum SingletonDemo implements Runnable {
    INSTANCE( "Alice" , 10_000 );

    String name;
    Integer salary;
    UUID uuid;

    SingletonDemo ( String name , Integer salary ) {
        System.out.println( "DEBUG - Constructing `SingletonDemo` enum at " + Instant.now() );
        this.name = name;
        this.salary = salary;
        this.uuid = UUID.randomUUID();
    }

    @Override
    public void run () {
        // CAUTION: Be sure you make this method thread-safe!
        System.out.format( "Thread %s is starting. uuid: %s\n" , Thread.currentThread().getName() ,this.uuid.toString() ); // Calling getters as I did here may not be thread-safe without further precautions (synchronization, etc.).
    }

    public static void main ( String[] args ) {
        Thread t1 = new Thread( SingletonDemo.INSTANCE );
        Thread t2 = new Thread( SingletonDemo.INSTANCE );
        Thread t3 = new Thread( SingletonDemo.INSTANCE );
        t1.start();
        t2.start();
        t3.start();
    }
}

When run.

DEBUG - Constructing SingletonDemo enum at 2019-01-30T00:48:46.614462Z

Thread Thread-0 is starting. uuid: a2825344-fb15-45d1-a6e4-239fc3bdf3c5

Thread Thread-2 is starting. uuid: a2825344-fb15-45d1-a6e4-239fc3bdf3c5

Thread Thread-1 is starting. uuid: a2825344-fb15-45d1-a6e4-239fc3bdf3c5

Thread Safety in Java Singleton Classes, How to create thread-safe singleton class in Java using synchronization and Provide a public static method that will return the singleton class instance variable. For the first few threads when the instance variable is not initialized, multiple� That's a mutable thread-safe singleton where the INSTANCE field is set to volatile, and someFlag is also volatile but access to someFlag is not synchronized. Changes made to the singleton should

First your singleton constructor MUST BE private. Second, use an object as a mutex to prevent collisions.

public class RunnableSingleton implements Runnable
{
    private static volatile RunnableSingleton instance;
    private static final Object mutex = new Object();

    private RunnableSingleton() {}

    public static RunnableSingleton getInstance()
    {
        RunnableSingleton result = instance;
        if (result == null) {
            synchronized (mutex) {
                result = instance;
                if (result == null) {
                    System.out.println("Creating instance");
                    instance = result = new RunnableSingleton();
                }
            }
        }

        return result;
    }

    @Override
    public void run()
    {
        System.out.format("Thread %s is starting\n", Thread.currentThread().getName());
        getInstance();
    }
}

Now, call the getInstance() method in your main like this:

public class SingletonDemo
{
    public static void main(String[] args) {
        System.out.println("test");
        RunnableSingleton t = RunnableSingleton.getInstance();
        Thread t1 = new Thread(t);
        Thread t2 = new Thread(t);
        Thread t3 = new Thread(t);
        t1.start();
        t2.start();
        t3.start();
    }
}

This is the output of the implementation:

test
Creating instance
Thread Thread-0 is starting
Thread Thread-2 is starting
Thread Thread-1 is starting

How to make the perfect Singleton? - Keval Patel, In eager initialization, the instance of Singleton Class is created at the time of If yes, then our method (getInstance()) will return that old instance and if not then As you made your getInstance() class synchronized the second thread will one instance of the Singleton class by using cloning or using multiple class loaders. Thread Safe Singleton: A thread safe singleton in created so that singleton property is maintained even in multithreaded environment. To make a singleton class thread-safe, getInstance () method is made synchronized so that multiple threads can’t access it simultaneously.

The CERT Oracle Secure Coding Standard for Java, public static synchronized MySingleton getInstance() { return Instance; } } The MySingleton class need not be declared final because it has a Noncompliant Code Example (Visibility across Threads) Multiple instances of the Singleton class� Because a singleton instance is associated with the class loader that is used to load it, it is possible to have multiple instances of the same class in the Java Virtual Machine. This situation typically occurs in J2EE containers and applets. Technically, these instances are different classes that are independent of each other.

Singletons in Java, See how to implement the Singleton Design Pattern in plain Java. public synchronized static ClassSingleton getInstance() { The method's body has several operations (comparison, instantiation, and return). This issue does not lead to the presence of multiple singleton instances at a time, but when� I’d take a step back and ask myself what I was trying to achieve in my design. A singleton generally gives you two things: * A guaranteed single, shared instance * Global access From your question, you’ve come up with a design that wants one of tw

Thread-safe Singleton in Java using Double Checked Locking Idiom , In Singleton pattern, a class has just one instance throughout its lifetime and that instance is shared between multiple clients. (the singleton instance) is initialized or not, one without synchronization and other with synchronization. code on Singleton * @return Singelton instance */ public static Singleton getInstance() { if� The Singleton design pattern addresses all of the above concerns. With the Singleton design pattern you can: Ensure that only one instance of a class is created; Provide a global point of access to the object; Allow multiple instances in the future without affecting a singleton class’s clients

Comments
  • @ElliottFrisch Link is (a) obsolete and (b) irrelevant. There is no double-checked locking here,
  • Except, this is single-checked (therefore, insufficient) locking.
  • I posted an answer
  • Thanks @EJK for your reply. But I would like to understand further, yes I will make it private agreed. But let say two threads enter the if block and then there is synchronized (SingleTon.class) , so two threads should not enter to create the instance right?
  • If you synchronize the method, then the calling thread must acquire the class-level lock before it is able to make the call. That ensures that the first thread will be able to create the initial instance before any subsequent thread can enter the method. Subsequent threads will then see a non-null instance and thus the conditional prevents other threads from creating more instances.
  • It worked this way as you suggested. 1) private constructor and 2) SingleTon t = SingleTon.getInstance(); in my Demo class. I did not change anything in singleton method .
  • I am sure it will work 99.99% of the time if you skip step 2, however in a long running multi-threaded program there is the possibility that eventually the timing will align just right (or wrong for you) which would trigger the 2nd creation. Step 2 makes your code 100% bullet-proof.
  • I see, just one more thing. once the thread is inside method means it will not get the value which is already written by the previous thread? Sorry I am learning them
  • Thanks for your reply. But I have synchronized (SingleTon.class) {, so why is not synchronized?
  • Your synchronized block only starts inside the if statement. Take this possible example with two threads, A and B. Thread A checks the static variable: Does not exist. Thread B checks the static variable: Does not exist. A creates the instance and stores it. Afterwards (because of the synchronization) B creates the instance and stores it. The point is, the threads can stop before the synchronized block. The block will then be executed by both threads without further checks.
  • Helped me understand in depth! Excellent