1

I haven't understood what the code's purpose => DataProvider instance = sInstance; is in below method. Anyone help me to explain in detail ? Why don't use directly sInstance ?

private static volatile DataProvider sInstance = null;
 public static DataProvider getInstance() {
     DataProvider instance = sInstance;
      if (instance == null) {
          synchronized (DataProvider.class) {
              instance = sInstance;
              if (instance == null) {
                  instance = sInstance = new DataProvider();
              }
          }
      }
      return instance;
  }
Hien Nguyen
  • 744
  • 2
  • 7
  • 20

3 Answers3

1

It is used as a lazy initialization (e.i. only create the singleton instance when needed). The problem with this code is that it is broken. Apparently even when using the synchronize block, there is a posaibility that things goes wrong (due to raceconditions). So do not use this method if you want to be safe!

Alternatives: Using a direct assignment (like you sugessted);

private static volatile DataProvider sInstance = new DataProvider();

Or using a enum (as suggested by @MadProgrammer);

public enum DataProvider
{

    INSTANCE;

    // singleton content
}
n247s
  • 1,898
  • 1
  • 12
  • 30
1

According to the book Prentice.Hall.Effective.Java.2nd.Edition.May.2008 of Joshua Bloch,

In particular, the need for the local variable result may be unclear. What this variable does is to ensure that field is read only once in the common case where it’s already initialized. While not strictly necessary, this may improve performance and is more elegant by the standards applied to low-level concurrent programming. On my machine, the method above is about 25 percent faster than the obvious version without a local variable.

Hien Nguyen
  • 744
  • 2
  • 7
  • 20
1

The main reason is Volatile. As @Hien Nguyen's answer, it improve 25% performance. Cause Volatile is always get data from main memory instead of cache, so it's too slow. Declare instance = sInstance to avoid read data from main memory multiple time (slow). There're 3 time we read data from sInstance if we don't use temp variable, so we use temp variable will imporve performance.

See this topic to understand why access Volatile is slow: Why access volatile variable is about 100 slower than member?

Your answer maybe the same as this topic: Java: using a local variable in double check idiom