☕ Java Intermediate

What is the synchronized keyword in Java?

Why Interviewers Ask This

This tests whether you can apply Java knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.

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.

Pro Tip

Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a Java codebase.