Java / Java Concurrency and Multi Threading in Java 17 and Java 21 Interview questions
What is the purpose of the synchronized keyword?
The synchronized keyword provides mutual exclusion: it ensures that only one thread at a time can execute a block of code or method that is guarded by the same lock, called a monitor.
You can apply it to an instance method (locks on this), a static method (locks on the class object), or an arbitrary block (locks on a chosen object), giving you control over exactly how much code and which lock is involved.
public synchronized void increment() { counter++; // only one thread executes this at a time per instance }
Besides mutual exclusion, entering and exiting a synchronized block also establishes a happens-before relationship, which guarantees that changes made by one thread before releasing the lock are visible to the next thread that acquires the same lock. This makes it a tool for both atomicity and memory visibility.
More Related questions...