Geeks With Blogs
Saqib Ullah BootStrapper Know How

In this blog I want to describe you three ways how to write singleton class that is thread safe.

First Class

public
sealed class TSSingleton
{
private static volatile TSSingleton instance = null
;
private static object syncObj = new object
();
// make the default constructor private,
// so that no can directly create it.
private
TSSingleton(){}
// public property that can only get
// the single instance of this class.
public static TSSingleton
Instance
{
get
{
// only create a new instance if one doesn't already exist.
if (instance == null
)
{
// use this lock to ensure that only one thread is access
// this block of code at once.
lock
(syncObj)
{
   if (instance == null
)
   instance = new TSSingleton
();
}
}
// return instance where it was just
// created or already existed.
return
instance;
}}
}

Second Class

sealed class MysingleTon

    // Static members are lazily initialized.
    // .NET guarantees thread safety for static initialization
 
   private static readonly MysingleTon instance = new MysingleTon(); 
   public static MysingleTon GetInstance()
   {
      return instance;
    }
 }

Thrid Class

sealed class Singleton
{
  private Singleton() { }
  public static readonly Singleton TheInstance = new Singleton();
}

I use last example of singleton class.

Posted on Monday, March 26, 2007 7:52 PM OOPs | Back to top


Comments on this post: Three Singleton Classes, but use only ONE.

# re: Three Singleton Classes, but use only ONE.
Requesting Gravatar...
...very good post

P.S. - yeh rang barangi font kiun use kia hai aap ne, parhne me mushkil ho rahi hai.
Left by Murtaza on Apr 04, 2007 12:53 AM

# re: Three Singleton Classes, but use only ONE.
Requesting Gravatar...
Holistic piece of codes.....
Left by gfax on Aug 05, 2007 7:53 AM

Your comment:
 (will show your gravatar)


Copyright © Saqib Ullah | Powered by: GeeksWithBlogs.net