Java:singleton, static variable and thread safety

multithreading, singleton, static, thread-safety
class MyClass{private static MyClass obj;public static MyClass getInstance(){    if(obj==null)    {        obj = new MyClass();    }    return obj;}

In the above java code sample, because obj is a static variable inside the class,
will getInstance still be non-thread safe? Because static variables are shared by all threads, 2 simultaneous threads shall be using the same object. Isnt it?

Vipul Shah

Best Solution

Because static variables are so widely shared they are extremely un-thread safe.

Consider what happens if two threads call your getInstance at the same time. Both threads will be looking at the shared static obj and both threads will see that obj is null in the if check. Both threads will then create a new obj.

You may think: "hey, it is thread safe since obj will only ever have one value, even if it is initialized multiple times." There are several problems with that statement. In our previous example, the callers of getInstance will both get their own obj back. If both callers keep their references to obj then you will have multiple instances of your singleton being used.

Even if the callers in our previous example just did: MyClass.getInstance(); and didn't save a reference to what MyClass.getInstance(); returned, you can still end up getting different instances back from getInstance on those threads. You can even get into the condition where new instances of obj are created even when the calls to getInstance do not happen concurrently!

I know my last claim seems counter-intuitive since the last assignment to obj would seem to be the only value that could be returned from future calls to MyClass.getInstance(). You need to remember, however, that each thread in the JVM has its own local cache of main memory. If two threads call getInstance, their local caches could have different values assigned to obj and future calls to getInstance from those threads will return what is in their caches.

The simplest way to make sure that getInstance thread safe would be to make the method synchronized. This will ensure that

  1. Two threads can not enter getInstance at the same time
  2. Threads trying to use obj will never get a stale value of obj from their cache

Don't try to get clever and use double checked locking: