Command Palette

Search for a command to run...

Back to the lesson: Topic 13.5 — Locks, Conditions and wait/notify
Core Java · Example 3 of 3 Java 5+

tryLock: don't wait if the lock is busy

Threads often need to wait for something (an item in a queue, free space, a signal). The built-in way is wait/notifyAll on a synchronized object; since Java 5, ReentrantLock with Condition does the same with more control: timeouts, interruptible waiting, fairness and several separate wait queues.

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

Rewrite the bakery example using ArrayBlockingQueue instead of hand-written wait/notify.

Explain it without notes

01

Why must wait be called in a loop?

02

When would you choose ReentrantLock over synchronized?

03

What is the advantage of two Conditions over one notifyAll?

tryLock: don't wait if the lock is busy Java 5+
Sign in to run this example in your browser.

Expected output

tryLock while another thread holds it: false
held by another thread? true
tryLock after release: true