views:

80

answers:

2
+1  Q: 

Singleton Instance

I know there are lot of ways to implement a thread safe singleton pattern like (Double Check Locking , static readonly method, lock method) but i just tried below code

static void Main(string[] args)
{           
    for (int i = 0; i <= 100; i++)
    {
        Thread t = new Thread(new ParameterizedThreadStart(doSome));
        t.Start(null);               
    }
    Console.ReadLine();
}

private static void doSome(object obj)
{           
    MyReadOnly obj1 = MyReadOnly.getInstance;
    Console.WriteLine(obj1.GetHashCode().ToString());
}   

class MyReadOnly
{
    private static  MyReadOnly instance  = new MyReadOnly();
    int counter = 0;

   // static MyReadOnly()
   // {
   // }  treat is as commented code.

    public static MyReadOnly getInstance { get { return instance; } }
    private MyReadOnly()
    {
        Console.WriteLine((++counter).ToString());
    }       
}

when i see the output of this program , i see just single object created (because of same hashcode)

how to prove that this code is not thread safe?

EDIT

removing static constructor which causes some confusion

+2  A: 

This is actually thread-safe code because you are (indirectly) using static constructor to create the instance (And CLR guarantees invocation of static constructor is thread-safe manner on/before access to any other type member).

VinayC
@VinayC : Thanks for youyr answer vinay.
saurabh
+4  A: 

That code is thread-safe due to the nature of type initializers in .NET. The type initializer is guaranteed to run exactly once, and if two threads try to run it at the same time, one will do so and the other will block.

See my article on singleton implementation for more details.

Jon Skeet
@Jon : Thanks , actually i have read your artical on the below site http://www.yoda.arachsys.com/csharp/singleton.html but is it the right way to implement a singleton or is this can be used as a pattern
saurabh
@saurabh: The code you've given *is* basically one of the patterns on the page.
Jon Skeet