Q43: How does the synchronized keyword work under the hood using Intrinsic Monitors?
Every Java Object possesses an Intrinsic Lock (Monitor).
- Synchronized Instance Method: Locks on
thisobject instance. - Synchronized Static Method: Locks on the class
Classobject (TargetClass.class). - Synchronized Block: Locks on a specified reference object.
Under bytecode execution,
monitorenteracquires the monitor andmonitorexitreleases it, ensuring mutual exclusion and cache flushing.
Key Takeaways
- Enforces mutual exclusion across threads accessing shared state.
- Uses bytecode
monitorenter/monitorexitdirectives on Object monitors.
Knowledge Check
What monitor object is locked when executing a synchronized static method?