☕ 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.
More Java Questions
View all →- Intermediate What is the Java Collections Framework?
- Intermediate What is the difference between ArrayList and LinkedList?
- Intermediate What is HashMap in Java and how does it work internally?
- Intermediate What is the difference between HashMap and HashTable in Java?
- Intermediate What is the difference between HashMap and LinkedHashMap?