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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With