philiplaureano / LinFu

A framework that adds mixins, inversion of control, DbC, and other language features to the Common Language Runtime.
http://www.codeproject.com/KB/cs/LinFuPart1.aspx
206 stars 30 forks source link

threading bug in SingletonFactory<T> #14

Open msironi opened 13 years ago

msironi commented 13 years ago

SingletonFactory.CreateInstance has a threading bug:

        if (_instances.ContainsKey(key))
            return _instances[key];

        lock (_lock)
        {
            T result = _createInstance(request);
            if (result != null)
            {                    
                _instances[key] = result;
            }
        }

The read check is done outside the lock so it is possible multiple threads could not find the singleton, then try to create it, leading to more than 1 singleton instance getting created. Either the read needs to be done inside the lock or a second copy of it needs to be pasted into the lock (for lazy locking). If it were up to me I'd do the latter. :)

        if (_instances.ContainsKey(key))
            return _instances[key];

        lock (_lock)
        {
            if (_instances.ContainsKey(key))
                return _instances[key];

            T result = _createInstance(request);
            if (result != null)
            {                    
                _instances[key] = result;
            }
        }