Synchronized method is used to lock an object for any shared resource. When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the thread completes its task.
Where can synchronized be used?
The synchronized keyword can be used to mark four different types of blocks:
- Instance methods.
- Static methods.
- Code blocks inside instance methods.
- Code blocks inside static methods.
What is synchronization used for?
Synchronization forms the basis of the execution of multiple threads asynchronously in a multithreaded application. It provides the means to achieve the sharing of resources such as file handling, network connections and memory by coordinating threads and processes to avoid data corruption.