4

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').

2

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

So while thread 1 runs methodA() in a specific instance, thread 2 can't run methodA(), can't run methodB(), and can't run methodC()?
Thanks :) Will accept the answer when the 7 minuts are up

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.