Aviv Cohn
Aviv Cohn

Reputation: 17243

Regarding synchronized methods in Java

I have a question about synchronization of methods in Java.

Consider a class with 3 synchronized methods.

class MyClass{

    public synchronized void methodA(){ ... }

    public synchronized void methodB(){ ... }

    public synchronized void methodC(){ ... }

}

Consider myObject, an instance of myClass. Which of the following is true?

Option 1:

It's impossible for a thread to run any synchronized method in myObject, while a different thread is running any synchronized method in myObject.

For example, while thread 1 is running methodA() of the instance myObject, thread 2 can't run any of the methods methodA(), methodB() and methodC().

Option 2:

It's impossible for a thread to run a specific synchronized method in myObject, while that specific method is being run by another thread.

For example, while thread 1 is running methodA() of the instance myObject, thread 2 can't run the method methodA(), but can run methodB() or methodC(). (Meaning, the three synchronized methods aren't 'connected').

Upvotes: 4

Views: 88

Answers (1)

kraskevich
kraskevich

Reputation: 18576

The first option is true because there is basically one lock used for all the methods.

Upvotes: 3

Related Questions