Possible Duplicate:
The need for volatile modifier in double checked locking in .NET
Given the following code snippet, which can be executed by more than one thread at once, would the volatile keyword be required to ensure that the 'real value' of connected
is always read from the memory and not a cache?
(Assume that Disconnect()
will only be called once (i.e. if it doesn't work properly the first time and the value of connected
is read as false, it's not going to be attempted again)).
public class MyClass
{
private readonly object syncRoot = new object();
private bool connected;
public void Disconnect()
{
if (connected)
{
lock (syncRoot)
{
if (connected)
{
// log off here
// ...
connected = false;
}
}
}
}
public void Connect()
{
lock (syncRoot)
{
// blah
// blah
connected = true;
}
}
}
My feeling is that if double checked locking is used then it does need to be marked volatile since if it reads the incorrect value the first time, then it's going to think it's actually disconnected and won't go into the lock statement. I also think that in this case double checked locking isn't appropriate / isn't going to provide any performance gain and just a normal lock would do the job.
I'd like someone to confirm or deny these thoughts.