synchronized and monitors

Intermediate Algorithms and Data Structures English
Also available: Deutsch
Created by Best · 16.08.2026 at 09:13 UTC

synchronized in Java locks a monitor (object). Only one thread holds the lock. Visibility and atomic sections are thus ensured (happens-before).

Coarse locks can slow down performance; fine locks are prone to errors.

Where used

Classic JVM mutual exclusion. This is foundational before moving on to java.util.concurrent, locks, and lock-free structures.

Depth

Any Java object can serve as a monitor. A synchronized block acquires its intrinsic lock, executes the protected section, and releases the lock upon exit, even in the case of exceptions. Only code that uses the same monitor collectively protects the same invariant.

Exiting a monitor publishes previous changes; later acquiring the same monitor makes them visible. Synchronized thus regulates both mutual exclusion and memory order. Choosing a private, stable lock object prevents unintended external lock coupling.

Difficulty levels

  1. Determine the monitor of an instance method and a static method.
  2. Protect all accesses to an invariant with the same lock.
  3. Balance the scope of locking between safety and parallelism.

Pitfalls

Two different lock objects do not protect against each other. Publicly accessible or changing lock objects are also risky. Multiple locks in inconsistent order can lead to a deadlock.

University approvals: 0
Tasks
Question 1

What does synchronized do on an object?

Question 2

Two methods protect the same field with two different lock objects. What is the problem?

Question 3

Implement LockedBox. set and get should use the object's monitor.

Hint

A synchronized block on the current object is written as synchronized (this) { ... }.

Starter code is prefilled; replace TODO blocks with your solution.
1 test case will be used for grading
Run checks runtime behavior only. Final correctness is evaluated when you submit.
Card Info
  • Topic: Algorithms and Data Structures
  • Difficulty: Intermediate
  • Completed: 0 users
Creator
Best
Best
BestBuddy