synchronized and intrinsic locks
On This Lesson 4 topics
This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.
In this lesson
use synchronized correctly.
Planned topics
- Every object has an intrinsic lock;
synchronizedgives mutual exclusion and visibility. - Synchronize the whole compound action, and use the same lock everywhere the data is touched.
- Do not lock on mutable fields, public objects, or
String/boxed values; use a private final lock object. - It is reentrant; keep critical sections short; never call unknown code while holding a lock.
wait/notifyexist but higher-level tools are usually better.
Draft outline details
Demonstration
private final Object lock = new Object();
void reserve(int qty) { synchronized (lock) { if (stock >= qty) stock -= qty; } }Check your understanding
Why not synchronized(this) in a public class?
Show answer
Outside code can lock the same object and interfere.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.