Java Synchronization Explained
The `synchronized` keyword in Java is used to implement a mechanism for thread synchronization. It can be applied to methods or code blocks, ensuring that only one thread can enter the synchronized method or code block at the same time, thus ensuring thread safety.
The underlying principles are as follows:
- The “synchronized” keyword is implemented based on the object lock mechanism. Each object has a lock associated with it, and when a thread enters a method or code block synchronized, it first tries to acquire the object’s lock.
- If the lock is acquired, the thread enters the critical section to execute the code, releases the lock after execution, and allows other threads waiting to acquire the lock to continue execution.
- If unable to acquire the lock, the thread will go into a blocking state, waiting for the thread holding the lock to release it before attempting to acquire the lock again.
- Once a thread acquires the lock, other threads cannot access it and must wait.
In Java, each object has a monitor lock (also known as an intrinsic lock or mutual exclusion lock). When a thread enters a synchronized method or code block, it attempts to acquire the object’s monitor lock.
When a thread acquires a lock, other threads are unable to access the lock and must wait. Once a thread finishes executing a synchronized method or code block, it releases the lock, allowing other threads to attempt to acquire it.
It is important to note that the granularity of the lock for the synchronized keyword is at the object level. This means that when a method of an object is synchronized, other threads cannot simultaneously call other synchronized methods of the same object. However, if multiple threads call methods of different objects, they will not block each other.