The keyword synchronized entitled to the method or block is used to prevent
it from being accessed simultaneously and save the state of an object from being
corrupted. There are two ways to implement the keyword synchronized:
If you want a method of an object to be executed by one thread at a time
then the method can be specified with the keyword synchronized. Method is
needed to be synchronized in situation where method can manipulate the state
of an object in ways that can corrupt the state if executed concurrently.
Synchronized Blocks (Statements):
It is the other way of synchronizing the code. In this approach, the block
is provided an object to allow execution of block of code to be synchronized
on the lock of this object.