Is there an advantage to use a Synchronized Method instead of a Synchronized Block?

后端 未结 23 1975
北荒
北荒 2020-11-22 04:29

Can any one tell me the advantage of synchronized method over synchronized block with an example?

23条回答
  •  不思量自难忘°
    2020-11-22 05:05

    Synchronized Method

    Pros:

    • Your IDE can indicate the synchronized methods.
    • The syntax is more compact.
    • Forces to split the synchronized blocks to separate methods.

    Cons:

    • Synchronizes to this and so makes it possible to outsiders to synchronize to it too.
    • It is harder to move code outside the synchronized block.

    Synchronized block

    Pros:

    • Allows using a private variable for the lock and so forcing the lock to stay inside the class.
    • Synchronized blocks can be found by searching references to the variable.

    Cons:

    • The syntax is more complicated and so makes the code harder to read.

    Personally I prefer using synchronized methods with classes focused only to the thing needing synchronization. Such class should be as small as possible and so it should be easy to review the synchronization. Others shouldn't need to care about synchronization.

提交回复
热议问题