← Lessons

quiz vs the machine

Diamond1900

Concurrency

The Software Transactional Memory

Wrapping shared memory access in optimistic transactions that commit or retry atomically.

6 min read · advanced · beat Diamond to climb

Transactions for memory

Software transactional memory, or STM, borrows the database idea of transactions for in memory data. You mark a block of code as atomic, and the runtime makes it appear to execute all at once with no other transaction seeing a partial result. You reason about correctness without manually placing locks.

Optimistic execution

STM is usually optimistic. A transaction runs without blocking and records what it touches:

  • It buffers writes privately and logs the version of each value it reads
  • At commit it validates that none of its read locations changed underneath it
  • If validation passes, the buffered writes are published atomically; otherwise the transaction aborts and retries from the start

Because aborts are automatic, the programmer never has to reason about lock ordering or deadlock.

What you give up

The convenience has costs. Re executing aborted transactions wastes work under high contention, and side effects like input or output cannot be rolled back, so they are restricted inside atomic blocks. STM trades raw performance and unrestricted effects for composable, deadlock free reasoning about shared state.

Key idea

STM runs shared memory access as optimistic transactions that validate and commit or abort, trading performance for deadlock free composable reasoning.

Check yourself

Answer to earn rating on the learn ladder.

1. How does an optimistic STM transaction commit?

2. What does STM free the programmer from reasoning about?

3. Why are side effects restricted inside atomic blocks?