Menu

GetOrAdd Ran My Factory Three Times
📰

GetOrAdd Ran My Factory Three Times

DEV Community: dotnet·Sukhpinder Singh·about 8 hours ago
#uj59hZG9
#devtodotnet#devto#dev#factory#callers
Reading 0:00
15s threshold

I had a client object that was expensive to build. It opens a pooled connection, reads a bit of config, and I only ever want one per name for the life of the process. So I did the obvious thing and cached it in a ConcurrentDictionary , keyed by name, built on first use with GetOrAdd . Thread-safe dictionary, lazy construction, done.

Then I noticed the startup logs. For a single key, "opening connection" showed up three times. Only one connection was actually in the dictionary afterward, and every caller was using it, so nothing looked broken downstream. But two connections had been opened and then quietly abandoned. On a cold start with a few of these firing at once, that adds up to real work nobody asked for.

The race is hiding in the one line I trusted most.

Where the extra calls come from

GetOrAdd(key, valueFactory) is not a lock around your factory. When several threads hit a missing key at the same moment, more than one of them can run the factory.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.