-1

Suppose I have those two implementations of a singleton:

1)

class Singleton {
    private static Singleton singleton;

    private Singleton(){}

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

2)

class Singleton {
    private static Singleton singleton;

    private Singleton(){}

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

What is the difference between those? In other words, is there a difference between using a synchronized block and using the synchronized keyword on the method for this case?

Bahadir Tasdemir
  • 10,325
  • 4
  • 49
  • 61
Ayoub Rossi
  • 410
  • 5
  • 18
  • The synchronized block provides more enhanced locking according to the scope. You can check out the differences from this link: http://www.java67.com/2013/01/difference-between-synchronized-block-vs-method-java-example.html – Bahadir Tasdemir Feb 04 '19 at 14:35
  • i'm not sure the duplicate target applies. (also the posted answer misses the point.) the second example uses piggybacking to assure that the change to the instance variable is made visible, so that's a different animal from what the target covers. Really though best advice here is: it would be better to use CDI or Spring or whatever and not have the Singleton class enforce its own singleness. – Nathan Hughes Feb 04 '19 at 14:51

1 Answers1

2

Synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread, all reads or writes to that object's variables are done through synchronized methods.

Synchronized Method

public Synchronized void foo() {
...
}

A synchronized block in Java is synchronized on some object. Only one thread executing can execute the code inside them at the same time. All other threads attempting to enter the synchronized block are blocked until the thread inside the synchronized block exits the block.

Synchronized block

private Object lock = new Object();

public void foo() {
synchronized(lock) {
...
}
}

https://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html

shasr
  • 325
  • 2
  • 5