手机站
网通分站
电信主站
密 码:
用户名:
热门关键字:  虚拟主机  cn域名  asd  ddd  域名注册
当前位置 : 主页>程序设计>Java技术>列表

如何正确实现多线程安全的singleton patterns

来源:互联网 作者:west263.com 时间:2008-02-23 点击:
西部数码-全国虚拟主机10强!40余项虚拟主机管理功能,全国领先!双线多线虚拟主机南北访问畅通无阻!免费赠送企业邮局,.CN域名,自助建站480元起,免费试用7天,满意再付款! P4主机租用799元/月.月付免压金!

Singleton Pattern


Short Introduction

Singleton pattern, described in the GOF Design Patterns book, is one of the most easily understandable and on of the most frequently used pattern. The goal of the singleton pattern is to make sure that there is only one instance of this class in the system and allow other classes Access this instance.

Case study

Today I tried to extend a exist MVC system in our project. Because only one instance of the Controller is needed in the system (typical Singleton pattern), a traditional singleton pattern was implemented here. The code is looked like:

public class Controller {

private static Controller instance;

public Controller()

{

// do something

}



public final static Controller getInstance(){



public final static Controller getInstance(){

(A)

if (instance == null) {

(B)

instance = new Controller();

}

return instance;

}

// some more methods

}

The above shown code is, just like it described in almost all Design patterns books, is beautiful and correct based on the traditional implantation of singleton pattern.

Just at this time, our Team leader came to me, saw the implementation and told me at the first second that the traditional implementation is NOT thread safe! Yes! It is thread unsafe, after I read the code once again. Why? Let us make try: two threads T1 and T2 try to call the class Controller. When T1 goes to the position (B) in the above shown code, it sleeps. Then comes T2 to the position (A) and checks whether an instance of the Controller exists. Because T1 sleeps at the position (B) before an instance will be created, T2 can go into the block and create a new instance of Controller. Now T1 is awake, and what will it do? Just create another instance of Controller, because it is already in the block! So, great! TWO instance are created! It is no more singleton!

The first simple idea that I got in the first second, as you estimated, is adding the key word synchronized before the method getInstance(). But this brings bad Performance. As we knew, the normally used solution for such a problem is to moving the synchronizing into the method. That means to building a synchronized block in the method. The code should be looked like this:

public class Controller {

private static Controller instance;

public Controller()

{

// do something

}

文章整理:西部数码--专业提供域名注册虚拟主机服务
http://www.west263.com
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!

共2页: 上一页 1 [2] 下一页
最新评论共有 0 位网友发表了评论
发表评论
评论内容:不能超过250字,需审核,请自觉遵守互联网相关政策法规。
用户名: 密码:
匿名
注册