Avoid synchronized(this) in Java?

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

    Avoid using synchronized(this) as a locking mechanism: This locks the whole class instance and can cause deadlocks. In such cases, refactor the code to lock only a specific method or variable, that way whole class doesn't get locked. Synchronised can be used inside method level.
    Instead of using synchronized(this), below code shows how you could just lock a method.

       public void foo() {
    if(operation = null) {
        synchronized(foo) { 
    if (operation == null) {
     // enter your code that this method has to handle...
              }
            }
          }
        }
    

提交回复
热议问题