It is a process by which it is ensured that only one thread uses a shared resource at a time, although 2 or Wore threads need access to it. Key to synchronization is the concept of the monitor ( an object that is used as a mutually exclusive lock which can be owned by only 1 thread at a given time)
Most multithreaded systems expose monitors as objects that your program must explicitly acquire & manipulate. But in Java, there is no class monitor. But instead, each object has its own implicit monitor that is automatically entered when one of the object's synchronized methods is called. Once a thread is inside a synchronized method, no other thread can call any other synchronized method on the same object. ie., synchronization support is built into the language.
The code can be synchronized in 2 ways:
- synchronized method
- synchronized block
Synchronized void call(String msg) prevents other threads from entering call() when already some thread is using it. Once a thread enters any synchronized method on an instance, no other thread can enter any other synchronized method on the same instance. However, non synchronized methods on that instance will continue to be callable.
Synchronized methods will not work in all cases. Eg., If a class does not use synchronized methods (i.e., not designed for multithreaded access) but still the access to the objects of that class has to be synchronized or if the class was created by a third party, its source code cannot be accessed, and thus 'synchronized' cannot be added to the appropriate methods within the class; In these situations, simply call the methods defined by this class inside a synchronized block.
Synchronized(object) //Reference to the object being synchronized
// statements to be synchronized