Net-Base Magazine

18.10.2026

Generics: Thread-safe cache with TMonitor and double-checked locking — where it fails in Delphi

Double-Checked Locking sounds like a clean cache optimization. In Delphi, however, it quickly causes rare, load-dependent failures in generic caches. This analysis of the misconception exposes the critical edge case — and provides robust alternatives for operation and maintenance.

18.10.2026

From magazine topic to project implementation

Relevant service and technical pages for this post

Monday, 09:12: A service has been running quietly for weeks. Then a load peak arrives, a new tenant, a new data set — and suddenly the event log shows a sporadic Access Violation. Not continuously. Not reproducible immediately. After a restart: quiet again. In the code there is a „clever“ spot that was supposed to improve everything: Double-Checked Locking in the generic cache. The phrase sounds familiar: „If the cache is warm, we can skip the lock.“

The mistake in that: Double-Checked Locking does not automatically make the thread-safe cache in Delphi faster and correct. It often only makes it harder to prove — and in the event of a fault considerably harder to debug. This misconception check shows where, in Delphi, System.TMonitor specifically goes wrong, which edge cases really matter in generic caches, and which patterns are better to operate in practice.

Thread-safe cache in Delphi: Misconception check „DCL + TMonitor is standard“

Mess- und Diagnose-Setup mit Notizblock und unscharfen Zeitreihen zur Analyse von Thread-Last und Cache-Zugriffen.
Debugging under load: telemetry instead of breakpoints.
Arbeitsplatzszene mit einem textfreien Diagramm zum Cache-Pre-Warming und parallelen Requests.
Pre-warming reduces contention without DCL risk.
Abstrakte Darstellung: paralleler ungesperrter Lesezugriff kollidiert mit einem Schreibzugriff auf ein Dictionary.
DCL weakness: an unsynchronized read collides with a concurrent write on the dictionary.

Double-Checked Locking (DCL) follows a simple idea: First check without a lock whether the cache entry exists. Only if it does not is a lock taken, it is checked again, and then built and stored. The intention is to eliminate expensive locks in the „warm state“.

The problem is not the idea but the precondition. DCL is only correct if it is ensured that a thread does not see a reference to an object whose initialization is not yet fully visible. Without defined memory fences (Memory Barriers), volatile semantics or atomics, reordering/visibility can cause another thread to consider something present „too early“.[Source] The Error-Prone documentation is Java-centered, but the core is language-agnostic: DCL depends on clear rules of the memory model, not on gut feeling.

For Delphi a second point is added: System.TMonitor is documented as a monitor mechanism (Enter/Exit/TryEnter) plus condition-variable behavior (Wait/Pulse/PulseAll).[Source] This helps with correct waiting and signaling. What the DocWiki does not provide in this form, however, is an explicit assurance that every form of DCL publication would be safe without additional measures. This gap is practically relevant: anyone using DCL must be able to argue correctness — not just hope for performance.

Delphi-specific pitfall: TMonitor is not always the monitor

Before even discussing locks, a short reality check is worthwhile: In Delphi there are two prominent TMonitor types with completely different meanings. System.TMonitor is the threading monitor. Vcl.Forms.TMonitor describes a display monitor in a multi-monitor setup.[Source]

That sounds like a beginner’s trap, but it also appears in large codebases: Units are pulled in, names are shortened in discussions, someone says „we use TMonitor“, and suddenly half mean something else. A practical countermeasure: when it is about synchronization, code (or architecture notes) should unambiguously state System.TMonitor — if necessary fully qualified so there is no debate.

Where Double-Checked Locking actually fails in Delphi

When DCL goes wrong, it rarely looks like a „classic“ synchronization error. It appears as random chaos. Especially with generic caches this is dangerous, because the cache is then present in many modules and errors propagate over large distances.

1) Visibility and partial initialization: reference „present“, contents not stable

The typical DCL damage: Thread A constructs an object, writes the reference somewhere (cache, field, dictionary value). Thread B checks without a lock, sees „present“ and uses it. If A has made the reference visible but it is not guaranteed that all initialized fields, internal lists or dependent structures are already visible to B, a state arises that appears logically impossible: an object exists, but an internal field is still default or nil. This is precisely the core of the DCL warnings: without memory-model guarantees another thread can see a reference before the initialization has been fully „published“.[Source]

Why is this so unpleasant? Because the crash often does not occur in the cache. It happens later — when accessing a property that was expected to be guaranteed. The stack trace then points to completely different areas (mapper, serializer, data access), and the synchronization point appears innocent.

2) Container safety: TDictionary is not a parallel read container during concurrent writes

Many DCL variants focus on “object construction.” They forget the container. A TDictionary is not designed for one thread to write (Add/Insert/Resize/Rehash) while another thread reads without a lock (TryGetValue/ContainsKey). Even if the value construction were perfectly published, accessing the dictionary internals can collide, for example during Rehash/Resize. DCL thus becomes not only a visibility issue but a concrete data-structure conflict.

This is the moment when DCL becomes particularly insidious: the unlocked first check is not merely an “optimization,” under certain circumstances it is simply an illegal access to a mutating container.

3) “In the worst case it will be built twice” is rarely harmless

DCL is often defended with a shrug: “Then it will just be built twice, but in the end it will exist once in the cache.” That only holds if the builder is idempotent and has no external effects. In real codebases caches frequently build things like prepared statements, RTTI metadata, parsers, mappers, configurations, HTTP clients or file-based resources. Double initialization can then duplicate resources, register states twice, or create timing windows that escalate under certain operational conditions.

4) Reentrancy and lock ordering: builder calls back into the cache

Another edge case that often gets missed in reviews: the builder for key X may indirectly call code that in turn uses the same cache (or a second cache). If lock orderings are not stable, deadlocks or prolonged blocking chains can arise. DCL amplifies this because developers quickly add extra locks (“only during build”) and then lose a clear view of which paths are locked when.

What the sources contribute to practice — and where the limits remain

The DocWiki on System.TMonitor is reliable when it comes to monitor behavior: Enter/Exit as mutual exclusion, Wait as atomic release and later reacquire of the lock, Pulse/PulseAll to wake waiting threads.[Source] From this follows for operation: If a cache works internally with conditions (e.g. “one thread builds, others wait”), that can in principle be expressed cleanly.

The limit: From this documentation one cannot derive a hard statement that DCL would always be correct without additional atomics/memory-barrier mechanisms. Precisely for that reason the conservative approach is interesting that Net-Base shows in a Delphi example for a type cache: access to the dictionary is consistently protected via TMonitor.Enter/Exit, so not DCL but “always lock”. In addition, Pre-Warming/Preload is recommended to reduce contention without increasing the correctness risk.[Source] Practical consequence: Anyone who introduces DCL to avoid locking should first check whether Pre-Warming and clean lock encapsulation provide the same benefit — with significantly fewer edge-case traps.

Robust alternatives: three cache patterns that are easy to operate

If the cache is to run stably in daily operation, throughput is not the only concern but also maintainability: How quickly can you determine in an incident whether the cache was involved? How clear is the locking concept? And how easily can the behavior be tested?

Pattern What it does well Typical weakness When appropriate
Always-Lock with System.TMonitor Simple auditability; every dictionary access is protected; clear failure domain Limited scaling when very many parallel reads occur Default for most caches in services and enterprise applications
Reader/Writer lock (e.g. TLightweightMREW) Many parallel reads; writes exclusive; less contention in a warm cache Complexity increases; read→write upgrade is error-prone Read-heavy caches with demonstrable contention
Pre-Warming / Preload Relieves the hot path; peak load decreases; behavior becomes more predictable Startup costs time; requires knowledge of keys or access patterns When typical keys are known (tables, tenants, document types)

Always-Lock: deliberately boring – and precisely for that reason reliable

Always-Lock means: reading and writing of the dictionary take place exclusively inside the monitor. At first this appears to be the anti-performance approach. In many business workloads, however, it is the fastest way to a system that remains manageable even six months from now. And: when contention occurs, you can measure it and address it deliberately (Pre-Warming, granularity, RW-Lock) – without risking fundamental correctness.

The cache implementation mentioned in the Net-Base example follows exactly this path: a shared dictionary is protected via TMonitor.Enter/Exit, instead of experimenting with DCL.[Source]

Reader/Writer-Lock: for truly read-mostly caches

If a cache is almost exclusively read after warmup, a Reader/Writer-Lock can make sense: many threads may read in parallel, only the write path is exclusive. This reduces blocking without leaving the container unprotected.

What matters here is less the class than the discipline: the code must strictly separate when it reads and when it writes. Half-optimizations („first read lock, then actually write lock“) quickly introduce complexity that later results in deadlocks or hard-to-explain wait states.

Pre-Warming: performance gain without synchronization gymnastics

Pre-Warming deliberately moves work out of the hot path. Instead of the first real request under load having to populate the cache, typical keys are loaded proactively. Net-Base explicitly recommends this approach as a complement to a monitor-protected cache to reduce contention.[Source]

When DCL really comes into play: a verifiable procedure

Sometimes there comes a point where Always-Lock is measurably no longer sufficient and an RW-Lock alone is inadequate or does not fit cleanly. Then DCL is discussed. At that stage you should treat it like a risk feature: with clear rules, tests and measurable criteria – not as a „micro-optimization“ in an incidental commit.

  1. Secure container access: Ensure that no unlocked access to a mutating TDictionary can occur. If writes are possible, reads must be protected (Monitor/RW-Lock) or the data structure/phase must be designed so that concurrent reading is guaranteed safe.
  2. Define a publication point: A value is considered „published“ only when it is fully initialized. Do not place a reference into the cache and then continue configuring it afterwards.
  3. Evaluate building twice: Check whether the builder has real side effects (handles, files, DB calls, registrations). If so, “build twice” is no longer a harmless worst case but an operational risk.
  4. Don’t guess memory visibility: If you want to read without a lock, you need a solid justification why a thread cannot observe a partially initialized state. Without an explicit basis, DCL becomes a hope pinned on implementation details.
  5. Reproducible load tests: Create a test that repeatedly queries the same key from many threads, including artificial delays in the builder. A single successful run is not evidence.

If point 4 cannot be answered cleanly, the result of the assessment is often simple: do not introduce DCL as the default, but address it via Pre-Warming, RW-Lock or cache granularity.

Debugging: Make cache race conditions visible instead of stepping over them

Breakpoints are often counterproductive for race conditions because they change the timing. It is more useful to provoke the conflict deliberately and log it in a way that reveals the timeline.

Symptoms consistent with DCL-/cache races

  • Sporadic access violations in Dictionary operations (TryGetValue, Add, ContainsKey) or in downstream code that uses supposedly ‚guaranteed-initialized‘ values.
  • Duplicate initialization of the same key despite the cache.
  • Deadlocks or long stalls that only occur under concurrency (especially with nested caches or lock chains).
  • Errors occur more in Release than in Debug, or only on specific machines.

Telemetry that actually helps

Log for cache accesses: Thread-ID, Key, Phase (First-Check, Lock-Enter, Second-Check, Build-Start, Build-End, Publish) and duration. When using monitors, optionally add TryEnter-based measurements to observe wait times. The goal is not „lots of logs“ but a clear sequence that shows during an incident whether container accesses occur outside protection or whether builds run in parallel.

Performance reality: Why TMonitor can appear „suddenly expensive“

A common trigger for DCL is real performance pain: lock contention eats throughput. Not every problem is an argument for DCL; often it is an indication of scaling details.

There are analyses that point to potential performance effects with TMonitor under high concurrency, for example due to cache-line contention/false sharing in internal structures.[Quelle] This is not a correctness argument against monitors, but a useful reminder: anyone who wants to optimize should measure first and then choose the appropriate means.

Typical, often lower-risk levers before DCL:

  • Pre-warming so the builder does not run under load.
  • Change cache granularity (fewer keys, fewer writes, fewer resizes).
  • Keep the write path short (do build work outside the lock, but keep container access protected).
  • RW lock instead of a monitor when reads dominate.

When the effort for a thread-safe cache is worthwhile — and when it isn’t

A generic cache is infrastructure. It pays off when it repeatedly replaces expensive work (RTTI-Scanning, complex mappers, parsers, configurations) and when real concurrency exists (service, job workers, task-based processing, multiple concurrent requests).

It is often overhead when:

  • the affected code paths run practically only on the UI thread,
  • the values are cheap and provide little measurable benefit,
  • the cache indirectly influences security- or billing-relevant logic, but the optimization is only speculative.

The point at which it becomes „clean“

Double-Checked Locking often looks like a „pro optimization“ in code review. In Delphi however, with generic caches it quickly becomes a mix of container risk, visibility questions and hard-to-reproduce failure patterns. The clean approach is usually: first establish correctness and verifiability (Always-Lock or Reader/Writer), then apply Pre-Warming and measurement, and only at the very end — if at all — discuss DCL for narrowly limited cases.

If you want to stabilize an existing cache or plan a modernization so that concurrency in operation does not become a lottery, a short technical assessment based on your concrete access patterns and load profiles is worthwhile. Contact us.

Sources and further information

The technical core statements were editorially classified based on the following external sources.

  1. DoubleCheckedLocking (errorprone.info)
    Double-Checked Locking is error-prone without guaranteed memory barriers/visibility; reordering can make a reference visible before full initialization.
  2. System.TMonitor – RAD Studio API Documentation (docwiki.embarcadero.com)
    System.TMonitor provides Enter/Exit/TryEnter as well as Wait/Pulse/PulseAll with defined monitor behavior, without an explicit DCL-publish guarantee in the documentation.
  3. Vcl.Forms.TMonitor – RAD Studio API Documentation (docwiki.embarcadero.com)
    Vcl.Forms.TMonitor describes a screen monitor and is not the threading monitor (terminology confusion).
  4. Delphi RTTI for mapping without magic | Net-Base (net-base-software-gmbh.de)
    Example of a Delphi cache: access is protected by TMonitor.Enter/Exit; additionally Pre-Warming is recommended to reduce contention.
  5. A Fistful of TMonitors – DelphiTools (www.delphitools.info)
    Analysis of TMonitor: possible performance-/contention effects (e.g. False Sharing) can affect locking under load.

For this topic, Delphi Tmonitor and Double-Checked Locking Delphi are also important. The article contextualizes these aspects clearly and shows what matters in everyday practice.

Discuss a project or modernization initiative with Net-Base.

Next step

When the topic becomes an actual project, architecture, existing systems and operations should be considered together from the outset.

We support not only with individual issues, but also when source snippets, legacy topics, or portal ideas are to be turned into a robust enterprise project.

  • Current state, target state and technical risks are assessed jointly.
  • REST, data access, portals and rollout are not deferred to a later stage as secondary consequences.
  • You can see early on which path is economically and operationally viable.

Share post

Share this post directly

LinkedIn, X, Facebook, WhatsApp und E-Mail sind sofort verfügbar. für Instagram bereiten wir Link und Kurztext direkt vor.

Email

Instagram opens in a new tab. The link and short text are copied to the clipboard beforehand.

Write comment

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert