Avoid synchronized(this) in Java?

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

    While you are using synchronized(this) you are using the class instance as a lock itself. This means that while lock is acquired by thread 1, the thread 2 should wait.

    Suppose the following code:

    public void method1() {
        // do something ...
        synchronized(this) {
            a ++;      
        }
        // ................
    }
    
    
    public void method2() {
        // do something ...
        synchronized(this) {
            b ++;      
        }
        // ................
    }
    

    Method 1 modifying the variable a and method 2 modifying the variable b, the concurrent modification of the same variable by two threads should be avoided and it is. BUT while thread1 modifying a and thread2 modifying b it can be performed without any race condition.

    Unfortunately, the above code will not allow this since we are using the same reference for a lock; This means that threads even if they are not in a race condition should wait and obviously the code sacrifices concurrency of the program.

    The solution is to use 2 different locks for two different variables:

    public class Test {
    
        private Object lockA = new Object();
        private Object lockB = new Object();
    
        public void method1() {
            // do something ...
            synchronized(lockA) {
                a ++;      
            }
            // ................
        }
    
    
        public void method2() {
            // do something ...
            synchronized(lockB) {
                b ++;      
            }
            // ................
        }
    
    }
    

    The above example uses more fine grained locks (2 locks instead one (lockA and lockB for variables a and b respectively) and as a result allows better concurrency, on the other hand it became more complex than the first example ...

提交回复
热议问题