mardi 13 février 2018

Proper locking pattern

I'm facing a little problem with locks in C# (but no matter the language, it's more an algorithmic question).

When I enter in a method, I take a read lock on an object. But if the given object is null (not initialized), I need to initialize it. So, I need to get a write lock on it. But, the problem is that I am already in a read lock zone.

Ex:

 public string LocalUid
        {
            get
            {
                        using (new CoalaReadLock(CoalaMongoDBConnector.adminLock))
                        { 
                            MongoClient mongo = CoalaMongoDBConnector.GetAdminClient();
                           // Do something...
                        }
                    }
                    return localUid;
                }
                return null;
            }
        }

and the GetAdminClient method is:

public static MongoClient GetAdminClient()
        {
            if (adminClient == null)
            {
                using (new CoalaWriteLock(adminLock))
                {
                    if (adminClient == null) // Double check locking pattern
                    {
                        adminClient = CreateAdminClient();
                    }
                }
            }
            return adminClient;
        }

So we clearly see that the writelock is asked in a readlocked zone :(

Any idea / best practice for this case ?

Aucun commentaire:

Enregistrer un commentaire