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
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
objand both threads will see thatobjis null in the if check. Both threads will then create a newobj.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
objback. If both callers keep their references toobjthen 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 whatMyClass.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 ofobjare created even when the calls to getInstance do not happen concurrently!I know my last claim seems counter-intuitive since the last assignment to
objwould seem to be the only value that could be returned from future calls toMyClass.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 toobjand 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
objwill never get a stale value ofobjfrom their cacheDon’t try to get clever and use double checked locking:
http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html