logoalt Hacker News

etermlast Tuesday at 10:03 PM0 repliesview on HN

There's a design in the .NET ConcurrentDictionary that is even more inviting:

  GetOrAdd(TKey, Func<Tkey,TValue> )
This lets you specify a key, and a method to run to generate a value to store if the key does not exist.

This is thread-safe, however it is not atomic much to the surprise of many that use it.

If you wrongly assume that the factory method can only execute once, you fall into a trap, since it actually can execute many times before the result is stored.

This can cause a problem if you use it for caching, because you might for example put an expensive calculation you want to cache there, only to find out cache expiration causes a stampede as the factory suddenly executes a lot at once.