Skip to content
Ameen Abozaid
Planned lessonMID-004-L03

synchronized and intrinsic locks

  • Lesson 3 of 9
  • Mid-level
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; synchronized gives 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/notify exist but higher-level tools are usually better.
Draft outline details

Demonstration

java
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.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.