java 单例初始化,java中的单例模式。懒惰的初始化

public static MySingleton getInstance() {

if (_instance==null) {

synchronized (MySingleton.class) {

_instance = new MySingleton();

}

}

return _instance;

}

1.is there a flaw with the above implementation of the getInstance method?

2.What is the difference between the two implementations.?

public static synchronized MySingleton getInstance() {

if (_instance==null) {

_instance = new MySingleton();

}

return _instance;

}

I have seen a lot of answers on the singleton pattern in stackoverflow but the question I have posted is to know mainly difference of 'synchronize' at method and block level in this particular case.

解决方案

1.is there a flaw with the above implementation of the getInstance

method?

It does not work. You can end up with several instances of your Singleton.

2.What is the difference between the two implementations.?

The second one works, but requires synchronization, which could slow down the system when you have a lot of accesses to the method from different threads.

The most straightforward correct implementation:

public class MySingleton{

private static final MySingleton _instance = new MySingleton();

private MySingleton(){}

public static MySingleton getInstance() {

return _instance;

}

}

Shorter and better (safely serializable):

public enum MySingleton{

INSTANCE;

// methods go here

}

Lazy initialization of singletons is a topic that gets attention way out of proportion with its actual practical usefulness (IMO arguing about the intricacies of double-checked locking, to which your example is the first step, is nothing but a pissing contest).

In 99% of all cases, you don't need lazy initialization at all, or the "init when class is first referred" of Java is good enough. In the remaining 1% of cases, this is the best solution:

public enum MySingleton{

private MySingleton(){}

private static class Holder {

static final MySingleton instance = new MySingleton();

}

static MySingleton getInstance() { return Holder.instance; }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值