synchronized, monitors, wait and notify question 25 of 180 junior
What exactly does synchronized lock?
- The block of code, so no two threads can run it at all
- Correct: One object's monitor: an instance method locks
this, a static method locks theClassobject, a block locks whatever you name - The class, always
- The variables mentioned inside the block
synchronized is mutual exclusion on one object's monitor, nothing more. Two threads can run the same
synchronized method at the same time if they are on different instances, and two threads can be inside
completely different methods and still block each other if those methods lock the same object.
Which object matters. A synchronized instance method and a synchronized static method in the same
class do not exclude each other: one holds the instance monitor, the other holds the Class monitor.
That mismatch is a real and common bug in code that has both a shared static cache and per-instance
state.
Quiz yourself on synchronized, monitors, wait and notify Suggest a correction