Java FAQ: Top Questions
28. What is the synchronized keyword in Java?
The synchronized keyword in Java ensures thread safety by allowing only one thread to access a method or block at a time, preventing race conditions.
- Synchronized Method: Locks the object’s monitor (instance or class).
- Synchronized Block: Locks a specific object, offering finer control.
-
Monitor:
Each object has a monitor;
synchronized
enforces mutual exclusion. - Use Case: Protects shared resources in multithreaded applications.