Java synchronize in singleton pattern

戏子无情 提交于 2019-12-05 03:26:28

It's just like any other class. It may or may not need further synchronization.

Consider the following example:

public class Singleton {

  private Singleton() {}

  public synchronized static Singleton getInstance() { ... }

  private int counter = 0;

  public void addToCounter(int val) {
    counter += val;
  }
}

If the class is to be used from multiple threads, addToCounter() has a race condition. One way to fix that is by making addToCounter() synchronized:

  public synchronized void addToCounter(int val) {
    count += val;
  }

There are other ways to fix the race condition, for example by using AtomicInteger:

  private final AtomicInteger counter = new AtomicInteger(0);

  public void addToCounter(int val) {
    counter.addAndGet(val);
  }

Here, we've fixed the race condition without using synchronized.

DeltaLima

Well, the purpose of the Singleton class is that there is at most one instance of it and that all Threads can access that same object.

If you would not synchronize the getInstance method the following could happen

Thread1 enters getInstance()

Thread2 enters getInstance()

Thread1 evaluates instance == null to true

Thread2 evaluates instance == null to true

Thread1 assigns instance and returns

Thread2 reassigns instance = new Singleton() and returns.

Now the threads both have a difference instance of the Singleton class which is what should have been prevented by this pattern.

Synchronizing prevents that both Threads can access the same block of code at the same time. So synchronization is needed in a multithreaded environment when you instantiate singleton classes.

Now assuming that multiple threads will attempt to access the Singletons methods at the same time synchronization might be necessary on those methods as well. Especially if they change data instead of only reading it this is true.

The correct(Best actually) way to use Singleton

private static singleton getInstance() {
    if (minstance == null) {
        synchronized (singleton.class) {
            if (minstance == null) {
                minstance = new singleton();
            }
        }
    }
    return minstance;
}

lazy initialization and thread safe solution:

public class Singleton {

    public static class SingletonHolder {
        public static final Singleton HOLDER_INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
        return SingletonHolder.HOLDER_INSTANCE;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!