Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java method synchronization improper usage?

Suppose there is the following code:

class MyClass {
    synchronized void myMethod1() {
        //code 
    }

    synchronized void myMethod2() {
        //code
    }
}

Now suppose myMethod1() and myMethod2() access distinct data; now if there are two threads, thread A calling only myMethod1() and thread B calling only myMethod2().

If thread A is executing myMethod1(), will thread B block waiting on myMethod2() even if they don't access the same data and there is no reason for this? As far as I know, synchronized methods use the monitor of this object for instance methods and that of MyClass.class object for static functions.

like image 554
Random42 Avatar asked Jul 05 '26 15:07

Random42


2 Answers

Your understanding of the situation is correct.

The typical solution is to have separate dedicated lock objects for the resources in question.

class MyClass {
    private final Lock lock1 = new ReentrantLock();
    private final Lock lock2 = new ReentrantLock();

    void myMethod1() {          
      lock1.lock();

      try {
        //code 
      } finally {
        lock1.unlock();
      }            
    }

    void myMethod2() {
      lock2.lock();

      try {
        //code 
      } finally {
        lock2.unlock();
      }    
    }
}
like image 112
Duncan Jones Avatar answered Jul 07 '26 04:07

Duncan Jones


You are correct in all your suppositions. In the case where no data is in common then there is no reason to synchronize at the method level.

like image 20
rolfl Avatar answered Jul 07 '26 04:07

rolfl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!