The Real Fullstack

The Deadlock

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

工程师8 分钟时间线模拟器代码挑战
javasqlpostgresql

此挑战尚未翻译为简体中文,你正在阅读英文版本。

任务:Reproduce the deadlock by choosing how lock acquisitions interleave, then choose a locking strategy that can never deadlock without serialising unrelated transfers.背景 · 学习目标 ▾

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.

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

学习目标

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

运行模拟以查看输出。

运行模拟
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);    }  }}

简化说明

Each transfer takes exactly two locks. Real databases detect deadlocks and abort one transaction after a timeout; the Java synchronized version would hang forever. 教学模型——数字用于说明行为,并非基准测试。

概念

建议先完成

相关挑战

参考资料