Avoid synchronized(this) in Java?

后端 未结 22 1216
予麋鹿
予麋鹿 2020-11-22 01:23

Whenever a question pops up on SO about Java synchronization, some people are very eager to point out that synchronized(this) should be avoided. Instead, they c

22条回答
  •  囚心锁ツ
    2020-11-22 01:55

    I'll cover each point separately.

    1. Some evil code may steal your lock (very popular this one, also has an "accidentally" variant)

      I'm more worried about accidentally. What it amounts to is that this use of this is part of your class' exposed interface, and should be documented. Sometimes the ability of other code to use your lock is desired. This is true of things like Collections.synchronizedMap (see the javadoc).

    2. All synchronized methods within the same class use the exact same lock, which reduces throughput

      This is overly simplistic thinking; just getting rid of synchronized(this) won't solve the problem. Proper synchronization for throughput will take more thought.

    3. You are (unnecessarily) exposing too much information

      This is a variant of #1. Use of synchronized(this) is part of your interface. If you don't want/need this exposed, don't do it.

提交回复
热议问题