How to show that the double-checked-lock pattern with Dictionary's TryGetValue is not threadsafe

后端 未结 5 692
南旧
南旧 2020-12-08 23:18

Recently I\'ve seen some C# projects that use a double-checked-lock pattern on a Dictionary. Something like this:

private static readonly object         


        
5条回答
  •  粉色の甜心
    2020-12-08 23:24

    Clearly the code is not threadsafe. What we have here is a clear case of the hazards of premature optimization.

    Remember, the purpose of the double-checked locking pattern is to improve the performance of code by eliminating the cost of the lock. If the lock is uncontested it is incredibly cheap already. Therefore, the double-checked locking pattern is justified only in the cases (1) where the lock is going to be heavily contested, or (2) where the code is so incredibly performance-sensitive that the cost of an unconstested lock is still too high.

    Clearly we are not in the second case. You're using a dictionary for heaven's sake. Even without the lock it will be doing lookups and comparisons that will be hundreds or thousands of times more expensive than the savings of avoiding an uncontested lock.

    If we are in the first case then figure out what is causing the contention and eliminate that. If you're doing a lot of waiting around on a lock then figure out why that is and replace the locking with a slim reader-writer-lock or restructure the application so that not so many threads are banging on the same lock at the same time.

    In either case there is no justification for doing dangerous, implementation-sensitive low-lock techniques. You should only be using low-lock techniques in those incredibly rare cases where you really, truly cannot take the cost of an uncontested lock.

提交回复
热议问题