Middle · Explain · ConcurrentDictionary factories may run more than once

Why can GetOrAdd publish one association after executing several value factories?

Think through your answer before opening the explanation.

Runtime & concurrency

Reveal answer and reasoning

ConcurrentDictionary protects its documented collection operations, but the valueFactory can execute outside its internal locks. Competing callers may therefore compute different candidates before one association is retained. The successful callers in the controlled lesson fixture receive the retained value even though two callbacks ran. Association publication and execution of arbitrary candidate-construction code are different boundaries.

The sequential companion's one factory call does not establish concurrent exactly-once behavior. A common wrong answer performs an irreversible effect in the callback because the dictionary is thread-safe. Losing candidates may require explicit cleanup, and a throwing factory has its own caller outcome. A Lazy holder can sometimes defer work behind the retained association, but its mode, failure caching, removal, and generation lifetime still need a contract.

The map is not automatically a permanent exactly-once resource registry across removals or processes.

What a strong answer covers

  • Factories may execute outside dictionary locks.
  • One retained association does not imply one candidate computation.
  • Effects and losing-resource cleanup need explicit ownership.

Common pitfall

Putting nonrepeatable work in a raw GetOrAdd factory under an exactly-once assumption.

Follow-up questions

  1. What can a Lazy wrapper change, and what can it not promise?
  2. How does key removal change the resource lifetime?

Self-review

Choose what to revisit. These marks are your own assessment and are separate from lesson completion.

Primary references

Open lesson and code ↗

← All interview questions