Command Palette

Search for a command to run...

Back to the lesson: Topic 13.9 — Deadlock, Livelock and Starvation
Core Java · Example 1 of 2

Lock ordering makes transfers deadlock-free

With the naive version (lock from then to), this program can hang forever on a multi-core JDK.

A deadlock is threads waiting for each other forever, usually because they take the same locks in different orders. Livelock is threads busily reacting to each other without progress, and starvation is a thread that never gets a turn. Lock ordering, timeouts and fewer shared locks prevent them.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Explain how you'd make a transfer between two Accounts deadlock-free when accounts have no id field.

Explain it without notes

01

What four conditions must hold for a deadlock, and how does lock ordering prevent it?

02

How would you find the cause of a hung Java service?

03

What is livelock and how does jitter help?

Lock ordering makes transfers deadlock-free
Sign in to run this example in your browser.

Expected output

a=1000 b=1000 total=2000