Java Singleton and Synchronization

2019-01-04 15:26发布

Please clarify my queries regarding Singleton and Multithreading:

  • What is the best way to implement Singleton in Java, in a multithreaded environment?
  • What happens when multiple threads try to access getInstance() method at the same time?
  • Can we make singleton's getInstance() synchronized?
  • Is synchronization really needed, when using Singleton classes?

8条回答
孤傲高冷的网名
2楼-- · 2019-01-04 16:25

You can also use static code block to instantiate the instance at class load and prevent the thread synchronization issues.

public class MySingleton {

  private static final MySingleton instance;

  static {
     instance = new MySingleton();
  }

  private MySingleton() {
  }

  public static MySingleton getInstance() {
    return instance;
  }

}
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-01-04 16:27
public class Elvis { 
   public static final Elvis INSTANCE = new Elvis();
   private Elvis () {...}
 }

Source : Effective Java -> Item 2

It suggests to use it, if you are sure that class will always remain singleton.

查看更多
登录 后发表回答