Avoid synchronized(this) in Java?

后端 未结 22 1192
予麋鹿
予麋鹿 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:49

    Well, firstly it should be pointed out that:

    public void blah() {
      synchronized (this) {
        // do stuff
      }
    }
    

    is semantically equivalent to:

    public synchronized void blah() {
      // do stuff
    }
    

    which is one reason not to use synchronized(this). You might argue that you can do stuff around the synchronized(this) block. The usual reason is to try and avoid having to do the synchronized check at all, which leads to all sorts of concurrency problems, specifically the double checked-locking problem, which just goes to show how difficult it can be to make a relatively simple check threadsafe.

    A private lock is a defensive mechanism, which is never a bad idea.

    Also, as you alluded to, private locks can control granularity. One set of operations on an object might be totally unrelated to another but synchronized(this) will mutually exclude access to all of them.

    synchronized(this) just really doesn't give you anything.

提交回复
热议问题