Software Transactional Memory
STM lets threads read and write shared memory inside atomic transactions that retry on conflict, replacing fine-grained locks with optimistic concurrency.
Definition
Software transactional memory is a concurrency control mechanism in which shared-memory accesses occur inside transactions that commit atomically or abort and retry when a conflict is detected.
Context and scope
It appears in languages such as Haskell and Clojure and in designs where lock discipline is hard to enforce manually.
Common misconceptions
- STM eliminates all blocking and contention
- a transaction can perform arbitrary side effects safely
Anti-patterns
- performing irreversible IO inside a transaction that may retry
- using STM for long transactions that thrash under load
Related concepts
Related examples
Authoritative source
Definition
Software transactional memory is a concurrency control mechanism in which shared-memory accesses occur inside transactions that commit atomically or abort and retry when a conflict is detected.
It appears in languages such as Haskell and Clojure and in designs where lock discipline is hard to enforce manually. Compared to simpler alternatives, this concept fits best when the trade-off it represents is the one the system actually cares about.
When to use it
A common use case is applying it at the boundary where the cost of getting it wrong is highest, and the scenario usually involves a concrete guarantee the system must uphold. Unlike an ad hoc approach, it makes that guarantee explicit, reviewable, and testable.
How it works
Transactions track the locations they read and validate them at commit time, so a conflict causes a retry rather than deadlock, but retries cost CPU under contention.
Side effects such as network calls or file writes must be deferred until after commit, because a retried transaction would otherwise repeat them.
Trade-offs and alternatives
STM is strongest for in-memory data with short transactions; it does not coordinate with a database and so cannot replace the database’s own transaction semantics. The main drawback is the extra complexity it introduces, so the benefit should clearly outweigh that cost before a team adopts it.
Common misconceptions
A persistent misconception is that STM eliminates all blocking and contention. Another is that a transaction can perform arbitrary side effects safely. For example, an engineer who assumes otherwise may design around a guarantee that does not actually exist, which only becomes obvious under load or failure.
Anti-patterns to avoid
Two recurring anti-patterns are to performing irreversible IO inside a transaction that may retry and to using STM for long transactions that thrash under load. Both tend to surface as hard-to-debug production issues rather than obvious test failures. Related concepts include Happens-Before Relationship, Thread-Local Storage, Asynchronous I/O.