本文介绍了Java以单例模式同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否需要将synchronize关键字应用于实现单例模式的类的每个方法?

Does the synchronize keyword need to be applied to each method of a class that implements the singleton pattern like this?

public class Singleton {

  private Singleton(){}

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

        return instance;
    }

  public void DoA(){
  }
}

由于Singletons不公开公共构造函数并且getInstance()方法是同步的,因此不需要同步方法DoA和Singleton类公开的任何其他公共方法。

Since Singletons don't expose a public constructor and the getInstance() method is synchronized, one does not need to synchronize method DoA and any other public methods exposed by the Singleton class.

这个推理是否正确?

推荐答案

这就像其他任何一样类。它可能需要或可能不需要进一步同步。

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

请考虑以下示例:

public class Singleton {

  private Singleton() {}

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

  private int counter = 0;

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

如果要从多个线程使用该类, addToCounter()有竞争条件。解决这个问题的一种方法是使 addToCounter()同步:

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;
  }

还有其他方法可以修复竞争条件,例如使用 AtomicInteger

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);
  }

在这里,我们已经修复了竞争条件而没有使用 synchronized

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

这篇关于Java以单例模式同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 17:17