Nested synchronized keyword

后端 未结 6 771
迷失自我
迷失自我 2020-12-29 01:30

I have this code in Java:

    public void doSomeThing() {
        synchronized (this) {
            doSomeThingElse();
        }
    }
    public void doSome         


        
6条回答
  •  囚心锁ツ
    2020-12-29 02:33

    You have already taken the monitor lock in the first synchronized. You should always ensure that the concurrency design does not make the performance impact huge.

    One way to ensure this is by synchronizing only the required statements/code.

    Let's say now your code will look something like this.

    public void doSomeThing()
     {
      synchronized (this) 
       {             
        synchronized (this) 
         {             
          // do something else         
         }           
       }     
     }
    

    Whereas this is what is required

    public void doSomeThing()
         {
           doSomeThingElse();     
         }
    public void doSomeThingElse()
    {
     synchronized (this) 
             {             
              // do something else         
             }
    }
    

提交回复
热议问题