The Real Fullstack

The Deadlock

Alice pays Bob while Bob pays Alice. Both requests hang until the database kills one. Why?

Ingénieur8 minSimulateur de chronologieDéfi de code
javasqlpostgresql

Ce défi n'est pas encore traduit en Français. Vous lisez la version anglaise.

Mission:Reproduce the deadlock by choosing how lock acquisitions interleave, then choose a locking strategy that can never deadlock without serialising unrelated transfers.Contexte · Objectifs d'apprentissage ▾

Pocketly's transfer service locks the source account, then the destination account. Monitoring shows rare bursts of “deadlock detected” errors in PostgreSQL and hung worker threads in the Java service — always when two users pay each other at the same moment.

Mission: Reproduce the deadlock by choosing how lock acquisitions interleave, then choose a locking strategy that can never deadlock without serialising unrelated transfers.

Objectifs d'apprentissage

  • Recognise the circular-wait condition behind deadlocks.
  • Prevent deadlocks with a global lock ordering.
  • Compare ordering, timeouts with back-off and coarse locks.
SimulationSimulé

Lancez la simulation pour voir la sortie.

Lancer la simulation
void transfer(Account from, Account to, long amount) {  synchronized (from) {          // T1 locks A, T2 locks B …    synchronized (to) {          // … then each waits for the other forever      from.withdraw(amount);      to.deposit(amount);    }  }}

Simplification

Each transfer takes exactly two locks. Real databases detect deadlocks and abort one transaction after a timeout; the Java synchronized version would hang forever. Modèle pédagogique — les chiffres illustrent un comportement, ce ne sont pas des benchmarks.

Concepts

Utile avant celui-ci

Défis liés

Références