Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

synchronized method vs synchronized block

If I have the following code

class SomeClass {    
...
public synchronized methodA() {
....
}

public synchronized methodB(){
....
}
}

This would synchronized on the 'this' object.
However, if my main objective here is to make sure multiple threads don't use methodA (or methodB) at the same time, but they CAN use methodA AND methodB concurrently,
then is this kind of design restrictive? since here thread1 lock the object (monitor object associated with the object) for running methodA but meanwhile thread2 is also waiting on the object lock even though methodA and methodB can run concurrently.
Is this understanding correct?

If yes, is this the kind of situation where we use synchronized block on a private dummy object so that methodA and methodB can run parallely with different thread but not methodA (or methodB) with different threads.
Thanks.

like image 653
TL36 Avatar asked Dec 17 '22 13:12

TL36


1 Answers

You've answered the question yourself: use one lock object per method and you're safe.

private final Object lockA = new Object();
private final Object lockB = new Object();
public void methodA() {
    synchronized(lockA){
        ....
    }
}
public void methodB() {
    synchronized(lockB){
        ....
    }
}

For more advanced locking mechanisms (e.g. ReentrantLock), read Java Concurrency in Practice by Brian Goetz et al. You should also read Effective Java by Josh Bloch, it also contains some items about using synchronized.

like image 107
Sean Patrick Floyd Avatar answered Jan 01 '23 19:01

Sean Patrick Floyd