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

后端 未结 23 2359
北荒
北荒 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 04:51

    In general these are mostly the same other than being explicit about the object's monitor that's being used vs the implicit this object. One downside of synchronized methods that I think is sometimes overlooked is that in using the "this" reference to synchronize on you are leaving open the possibility of external objects locking on the same object. That can be a very subtle bug if you run into it. Synchronizing on an internal explicit Object or other existing field can avoid this issue, completely encapsulating the synchronization.

提交回复
热议问题