Avoid synchronized(this) in Java?

后端 未结 22 1463
予麋鹿
予麋鹿 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条回答
  •  Happy的楠姐
    2020-11-22 01:48

    A lock is used for either visibility or for protecting some data from concurrent modification which may lead to race.

    When you need to just make primitive type operations to be atomic there are available options like AtomicInteger and the likes.

    But suppose you have two integers which are related to each other like x and y co-ordinates, which are related to each other and should be changed in an atomic manner. Then you would protect them using a same lock.

    A lock should only protect the state that is related to each other. No less and no more. If you use synchronized(this) in each method then even if the state of the class is unrelated all the threads will face contention even if updating unrelated state.

    class Point{
       private int x;
       private int y;
    
       public Point(int x, int y){
           this.x = x;
           this.y = y;
       }
    
       //mutating methods should be guarded by same lock
       public synchronized void changeCoordinates(int x, int y){
           this.x = x;
           this.y = y;
       }
    }
    

    In the above example I have only one method which mutates both x and y and not two different methods as x and y are related and if I had given two different methods for mutating x and y separately then it would not have been thread safe.

    This example is just to demonstrate and not necessarily the way it should be implemented. The best way to do it would be to make it IMMUTABLE.

    Now in opposition to Point example, there is an example of TwoCounters already provided by @Andreas where the state which is being protected by two different locks as the state is unrelated to each other.

    The process of using different locks to protect unrelated states is called Lock Striping or Lock Splitting

提交回复
热议问题