In a multithreaded application when you want the states of an object to be read and written in a synchronized way by multiple threads then you use synchronized
keyword.
The mechanism that Java uses to support synchronization is the monitor. Each object has a monitor associated with it. Synchronized block needs an object to work with, so that the threads in competition can compete and the winner thread can aquire the monitor.
Each non static method in java has an implicit this
object upon which the particular method is invoked. If you use synchronized
keyword in the method signature then it means you are depending upon the implicit this
object for synchronization. If you wish to depend upon any other object then you can use the synchronized
blocks and use the object reference in it.
Remember there may be various synchronized
blocks but the blocks with synchronized
block on same object will only gurantee the proper syncronized execution with respect to each other. Synchronized Blocks which have references of different objects do not force threads to work in synchronized way.
Thus Suppose when there is some threadA which modifies some states of an objectX and works with synchronized block with ObjectA. There may be another piece of code may be in some other class where some other threadB may be reading the states of the same objectX. Now threadB should also do the reading within a synchronized block with ObjectA so that states of objectX are read properly.