How Java's synchronized keyword works: the monitor, bytecode, and thread blocking

The article explains that Java synchronization relies on a single mechanism, the monitor, which any object can serve as, allowing only one thread to hold it at a time. It contrasts synchronized blocks and methods, showing via javap output that blocks compile to monitorenter and monitorexit instructions with an exception-handler path that guarantees release. Synchronized methods instead use an ACC_SYNCHRONIZED flag, with the JVM handling entry and exit at the call boundary. The author demonstrates that a thread waiting for a held monitor enters the BLOCKED state, observed in a live two-thread example where the holder sleeps inside its critical section. The piece also notes that Thread.sleep does not release locks it holds.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.



Discussion (0)
Log in to join the discussion and vote.
Log in