InvertIf VS Double lock pattern
Hey there, Resharper is giving conflicting warnings for InvertIf and the Double lock pattern.
Lets say you have the following code:
private static string GetSingleton()
{
if (component == null)
{
lock (Locker)
{
if (component == null)
{
try
{
component = GetModel(Version);
}
catch
{
component = "Exception retrieving device";
}
}
}
}
return component;
}
Resharper will tell your to invert the ifs to reduce nesting, resulting in the following code:
private static string GetSingleton()
{
if (component != null)
{
return component;
}
lock (Locker)
{
if (component != null)
{
return component;
}
try
{
component = Create();
}
catch
{
component = "Exception creating";
}
}
return component;
}
But then when I inspect the solution, I get the warning "Possible incorrect implementation of Double-Check Locking. Possible multiple write access to checked field"
Is this true? It seems weird since I followed resharpen's suggestions of refactoring. I don't know why my singleton would be implemented incorrectly when the ifs are inverted.
Any explaination, or is this a bug?
Please sign in to leave a comment.
Ron,
Feel free to follow and comment https://youtrack.jetbrains.com/issue/RSRP-457760 ticket.
Thanks!
Try making the field volatile, as the Code Inspection Wiki suggests:
https://confluence.jetbrains.com/display/ReSharper/Possible+multiple+write+access+in+double-checked+locking
The field is volatile. Still, if you invert the ifs, resharper is saying "Possible incorrect implementation of Double-Check Locking. Possible multiple write access to checked field"