hao
hao

Reputation: 655

Using synchronized blocks for different methods in the same class

I was reading on official tutorial on multithreading from oracle and I came cross this example (assuming c1 and c2 are never used together):

public class MsLunch {
    private long c1 = 0;
    private long c2 = 0;
    private Object lock1 = new Object();
    private Object lock2 = new Object();

    public void inc1() {
        synchronized(lock1) {
            c1++;
        }
    }

    public void inc2() {
        synchronized(lock2) {
            c2++;
        }
      }
    }
}

It is said that by using lock 1 & lock 2, it helps to reduce unnecessary blocking as compare to using the word this in the synchronized block.

However, I don't really see how this helps to reduce blocking as they have no dependency on each other. I have multiple threads each running these two methods at the same time and the performance is rather similar when I use the lock objects and this keyword.

Can someone help to explain my confusion here? Love to see the explanation with an example to illustrate the difference clearly.


Adding on to the discussion here, this post helped to clarify my doubts as well. Key point: Putting synchronized on a method means the thread has to acquire the lock on the object instance before entering that method

Upvotes: 1

Views: 403

Answers (1)

Mureinik
Mureinik

Reputation: 311018

You are using two different locks - one to protect inc1 and a different one to protect inc2. This means that thread X can run inc1 while another thread is running inc2. Had they used the same lock (regardless whether it's this or a different lock object), you would not be able to run them both concurrently. Thus, in theory at least, having two different locks should increase your performance in this scenario.

Upvotes: 3

Related Questions