Command Palette

Search for a command to run...

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

Backing off with tryLock

done[0]++ is safe here because it only runs while holding both locks.

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?

Backing off with tryLock Java 5+
Sign in to run this example in your browser.

Expected output

operations completed: 400