The Real Fullstack

The Deadlock

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

Engenheiro8 minSimulador de linha do tempoDesafio de código
javasqlpostgresql

Este desafio ainda não foi traduzido para Português (Brasil). Você está lendo a versão em inglês.

Missão:Reproduce the deadlock by choosing how lock acquisitions interleave, then choose a locking strategy that can never deadlock without serialising unrelated transfers.Contexto · Objetivos de aprendizagem ▾

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.

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

Objetivos de aprendizagem

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

Execute a simulação para ver a saída.

Executar simulação
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);    }  }}

Simplificação

Each transfer takes exactly two locks. Real databases detect deadlocks and abort one transaction after a timeout; the Java synchronized version would hang forever. Modelo educacional — os números ilustram comportamento, não são benchmarks.

Conceitos

Útil antes deste

Desafios relacionados

Referências