中国IT动力,最新最全的IT技术教程
最新100篇 | 推荐100篇 | 专题100篇 | 排行榜 | 搜索 | 在线API文档
首 页 | 程序开发 | 操作系统 | 软件应用 | 图形图象 | 网络应用 | 精文荟萃 | 教育认证 | 硬件维护 | 未整理篇 | 站长教程
ASP JS PHP工程 ASP.NET 网站建设 UML J2EESUN .NET VC VB VFP 网络维护 数据库 DB2 SQL2000 Oracle Mysql
服务器 Win2000 Office C DreamWeaver FireWorks Flash PhotoShop 上网宝典 CorelDraw 协议大全 网络安全 微软认证
硬件维护  CPU  主板  硬盘  内存  显卡  显示器  键盘鼠标  声卡音箱  打印机  机箱电源  BIOS  网卡  C#  Java  Delphi  vs.net2005
  当前位置:> 程序开发 > 编程语言 > Java > 综合文章
如何正确实现多线程安全的singleton patterns
作者:未知 时间:2005-07-27 22:31 出处:CSDN 责编:chinaitpower
              摘要:如何正确实现多线程安全的singleton patterns

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

    }

   

    public final static Controller getInstance(){ 

                        (A)

if (instance == null) {

                        (B)

            synchronized {

                        instance = new Controller();

            }

        }

return instance;

    }

 

// some more methods

}   

But This code is still thread unsafe! Why? Because it is only synchronized when an instance is created, the above described problem DOES still exist. T1 sleeps at (B), T2 goes through and create a new instance, T1 wakes up and create another one! If we move the synchronized block up to contain the whole if block, there is nothing difference with a synchronized method. So, synchronized is a bad idea.

We must find another way.

The Current most used  thread safe solution for this problem is to creating an instance of the class as class’s private property when the class is loaded. The instance can be accessed by calling the public getInstance() method. The correct code should be looked like:

 public class Controller {

     private static Controller instance = new Controller();

    public Controller()

    {

            // do something

    }

   

    public final static Controller getInstance(){ 

return instance;

    }

// some more methods

}   

One drawback of this solution is that an instance is created anyway, even if the instance will be never used.


关闭本页
 
首页 | 投资与合作 | 服务条款 | 隐私政策 | 收藏本站 | 设为首页 | 新用户注册 | 免责声明 | 使用帮助
Copyright ©2005-2008 chinaitpower.com All rights reserved. www.chinaitpower.com 版权所有