Before trying to know the advantages and disadvantages. Please help understand the fact that, "Synchronization" is REVERSE of "Concurrency". This means whatever code you make "Synchronized" will be executed "NON-CONCURRENTLY" by the threads.
"The problem at hand is to find the optimal solution so that MOST of the code remains unsynchronized but still
thread safe."
This implies that one should reduce the scope of the synchronized code as much as possible but keeping the code thread safe.
Synchronized blocks are there for the rescue.
Synchronized block:
Advantage:
1. Provides more granularity. In the sense, you can reduce the scope of the synchronized code.
2. Provides flexibility. In the sense one can include/exclude the code from the synchronized block without affecting the method signature.
Disadvantage:
1. When you declare a method itself as synchronized, then just by looking at the method signature one can understand that it is synchronized as against the synchronized blocks.
Synchronized Methods:
Advantage:
1. When you declare a method itself as synchronized, then just by looking at the method signature one can understand that it is synchronized as against the synchronized blocks.
Disadvantage:
1. Provides less granularity.
2. Less flexible.