Ankur
Ankur

Reputation: 11739

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.

Upvotes: 4

Views: 1626

Answers (3)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298898

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.

Upvotes: 9

Liv
Liv

Reputation: 6124

If my understanding is correct you want to allow thread T1 to run methodA() at the same time thread T2 runs methodB() -- but you don't want thread T1 to run methodA() at the same time thread T2 runs methodA() (and same for methodB) right? For this scenario you can't use just a simple synchronized method -- instead, as you said, you will need 2 dummy objects (one for methodA and one for methodB) to synchronize on. Or you could use the new Lock class -- one Lock instance per method.

Upvotes: 1

WhiteFang34
WhiteFang34

Reputation: 72039

If you want to allow running methodA() and methodB() concurrently but otherwise restrict each method to one thread then you need two separate objects to synchronize on. For instance:

class SomeClass {
    private final Object lockA = new Object();
    private final Object lockB = new Object();

    public void methodA() {
        synchronized (lockA) {
            // 
        }
    }

    public void methodB() {
        synchronized (lockB) {
            // 
        }
    }
}

Upvotes: 2

Related Questions