Singleton Thread-Safety Question

  • Thread starter Thread starter Cool Guy
  • Start date Start date
C

Cool Guy

In the following implementation of Singleton, is the instance constructor
guaranteed to execute only once regardless of how many threads try to
access it at one time?

class Test {
public static readonly Test Instance = new Test();

Test() {
// set up state. this mustn't execute more than once
}
}
 
Cool Guy said:
In the following implementation of Singleton, is the instance constructor
guaranteed to execute only once regardless of how many threads try to
access it at one time?

class Test {
public static readonly Test Instance = new Test();

Test() {
// set up state. this mustn't execute more than once
}
}

Yes, that's guaranteed to only execute once. There are some caveats
about ordering when there's potential for a deadlock, but in simple
situations like the above (which 99% of static initializers fall into)
it's fine.
 
Jon Skeet said:
Yes, that's guaranteed to only execute once. There are some caveats
about ordering when there's potential for a deadlock, but in simple
situations like the above (which 99% of static initializers fall into)
it's fine.

Could you give an example of one such caveat?
 
Cool Guy said:
Could you give an example of one such caveat?

Sure. It's not actually a matter of initializing twice, but of the
incompletely initialized state being visible temporarily. For instance:

using System;

public class A
{
static string Something = B.Bar;
public static string Foo = "Hello";
}

public class B
{
public static string Bar = "There";

static B()
{
Console.WriteLine ("In B, A.Foo='{0}'", A.Foo);
}
}

public class Test
{
static void Main()
{
Console.WriteLine (A.Foo);
}
}

The results are:
In B, A.Foo=''
Hello

There are further rules for multithreaded system - I suggest you look
in the CLI spec, section 9.5.3.3 of partition 1 for further details.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top