synchronized, monitors, wait and notify question 32 of 180 senior
Is an uncontended synchronized block expensive?
- Yes, it always makes a system call
- Correct: Cheap: a CAS on the object header, and the JIT may elide the lock entirely
- It costs nothing at all
- It costs the same as a contended one
An uncontended monitor is taken with a CAS on the mark word in the object header, no kernel involvement. Only when a second thread actually contends does the monitor inflate into a heavyweight one with an OS-level wait.
Two JIT optimisations go further. Lock elision removes the lock when escape analysis proves the object
never leaves the thread, which is why StringBuffer in a local variable costs the same as
StringBuilder. Lock coarsening merges adjacent synchronized blocks on the same object into one.
The nuance that dates a candidate: biased locking made repeated uncontended locking by the same thread free, and it is gone as of JDK 18. Advice that assumes it is now wrong.
Quiz yourself on synchronized, monitors, wait and notify Suggest a correction