So what is double checked loading
static Instance instance = null;
if(instance is not null)
{
lock(key)
{
if(instance is not null)
{
instance = new Instance();
}
}
}
return instance;
So why this is not advised
1. Some compiler creates statements as such, the value is initialized even before the constructor completes. So instance may not be null, even before 'new Instance()' completes, hence we get into issues.
2. To solve this make instance as volatile.
http://en.wikipedia.org/wiki/Double-checked_locking
http://www.yoda.arachsys.com/csharp/singleton.html
Thank god, i stand corrected now
So what is volatile - Historically it means the decorated variable can be modified by OS, threads etc, and disallows compiler from making optimizations
for example -
class Test
{
static int foo;
static void Main()
{
//new Thread(delegate() { Thread.Sleep(500); test.foo = 255; }).Start();
while (foo != 255) ; //this might be optimized to while(true); because
//foo is not updated anywhere - but it might have been
//by other system or threads etc.
Console.WriteLine("OK");
}
}
in C#,it means any writes is immediately flushed into memory(from Thread's Cache),
and when read it is always read from memory instead of cache.
http://en.wikipedia.org/wiki/Volatile_variable
http://stackoverflow.com/questions/133270/how-to-illustrate-usage-of-volatile-keyword-in-c-sharp
http://msdn.microsoft.com/en-us/library/x13ttww7%28v=vs.71%29.aspx
No comments:
Post a Comment