1

While implementing the Singleton pattern, could someone please explain the difference between:

Synchronized Static Method:

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

and Synchronized block inside a static method:

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

Why do we have to check instance==null twice in the second method and what is the advantage of the second method over the first?

takeradi
  • 3,661
  • 7
  • 29
  • 53
  • Word of advice: don't implement a Singleton this way, use [an enum](http://www.informit.com/articles/article.aspx?p=1216151&seqNum=3) (if you *really* need a Singleton...) – kryger Dec 03 '15 at 23:31

1 Answers1

1

In the second example you have to check instance==null twice because of race conditions - if two threads check this condition at the same time then both of them go further with the if statement. Then only one can enter into the critical section, but without null check again thread2 would override the value of instance

The difference is that the first one is coarse grained synchronization and the second one is fine grained:

  • in the first example you will obtain lock every time you call the function (it's slower)
  • in the second one you will probably obtain the lock only on the first function call (much faster due to not locking every time)
k0ner
  • 1,086
  • 7
  • 20
  • One important detail is missing from your explanation: [this idiom is broken and dangerous...](http://www.javaworld.com/article/2074979/java-concurrency/double-checked-locking--clever--but-broken.html) – kryger Dec 03 '15 at 23:28
  • I would not say "coarse-grained" and "fine-grained" here. Those terms usually refer to the number of locks used in a complex data structure. If every record in the structure has its own lock, and different threads can operate on different records at the same time, then that's the extreme of what people usually call that "fine-grained" locking. The opposite extreme, "coarse-grained locking", would be where one lock protects everything, and only one thread at a time can access anything. – Solomon Slow Dec 03 '15 at 23:52
  • @jameslarge so can't these terms be applied here as well? In the first case only one thread can access to the method in the second one multiple thread can access. – k0ner Dec 04 '15 at 00:11
  • Not sure what you mean by "access the method". The purpose of the locking in this case is to insure that two different threads don't end up using two different instances of the `Singleton` class. Both examples achieve that, but the second example has a flaw (see kryger's "broken and dangerous" link). – Solomon Slow Dec 04 '15 at 02:37