Code Inspection: Possible incorrect implementation of Double-Check Locking pattern. Possible multiple write access to checked field
Consider the following piece of code:
public class Foo
{
private static Foo instance;
private static readonly object padlock = new object();
public static Foo Get()
{
if (instance == null)
{
lock (padlock)
{
if (instance == null)
{
instance = new Foo();
}
}
}
return instance;
}
};
Given the above code, writes that initialize the Foo
instance could be delayed until the write of the instance value, thus creating the possibility that the instance returns an object in an uninitialized state.
In order to avoid this, the instance value must be made volatile
.
Last modified: 21 July 2022