☕ Java Intermediate

What is the synchronized keyword in Java?

Answer

The synchronized keyword is used to control access to a block of code or a method so that only one thread can execute it at a time, preventing race conditions. When applied to a method, the thread must acquire the intrinsic lock (monitor) of the object before executing. Synchronized on a static method uses the class's lock. You can also synchronize on a specific object: synchronized (sharedObject) { }. While synchronized ensures thread safety, it comes with performance cost (lock contention) and risk of deadlock. For fine-grained control, the java.util.concurrent.locks package provides more flexible alternatives like ReentrantLock.