The following article contains one of the most important concepts of Java, Synchronisation in Java, along with simple examples to get a proper idea of the concept.
Synchronization in Java
Basically Synchronization in Java is the process of allowing the threads to execute one after the other. It controls the access of multiple threads to a shared resource.
Java is a multithreaded language where multiple threads can run in parallel to execute the program. In a multithreaded environment, there is a necessity for synchronization of Java objects that share common resources concurrently. When two or more threads start within a program then there may be a situation of inconsistent results due to concurrency issues since multiple threads try to access the same resource at the same time.
Suppose multiple threads try to do a write operation; that may corrupt the data because one of the threads may overwrite the data or while one of the threads is opening the file at a time and another is closing the same file at the same time.
So there is a need for synchronization that ensures that only one thread can access the resource at a given time. This can be done by using the concept called monitor. In Java, each object is associated with a monitor that a thread can lock or unlock. Only one thread can hold or lock at a time on a monitor.
The following is the syntax of a synchronization block: