Reputation: 157
Suppose there is a class Test which has one synchronized method m1, and one non synchronized method m2, and an instance of Test, say obj.Two threads T1 and T2, try to access methods related to instance obj. What happens when T1 invokes obj.m1(synchronized method), and before it completes m1 execution, T2 invoked obj.m2(non-synchronized). Will T2 have to wait?
I was asked this question in an interview.
My Answer: T2 will continue to execute without any wait. T2 is accessing non-synchronized method, hence it does not need any lock.
The interviewer did not seem to agree with my answer, though when I asked him back about the correctness of my answer, he did not provide any input.
Please help me understand if I am missing something.
P.S. I have tried a test program already, and I see that my understanding is right. I am just wondering if there is any special scenario where this would not work as I explained to the interviewer.
Upvotes: 2
Views: 370
Reputation: 837
Well, You answer sure was correct, but i guess the small reply didn't made the interviewer happy or maybe he had higher expectations and wanted a very clear explanation for his question.
I wont be writing any code to answer your question, but i will state two points highlighting the basics of multi-threading
in java.
1) Each object has only one lock.
2) If two threads say T1 and T2 are trying to execute synchronized instance methods on the same object, then the thread which obtains the lock first will be able to execute the synchronized method and the other thread T2 will have to wait until T1 completes its execution or enters into blocking/waiting state for some handful number of reasons. In other words, No Thread T2 can not enter ANY (I repeat ANY)
synchronized
method for an object "obj" if Thread T1 already has a lock for the same objectobj
.3) If a Class has both synchronized and non-synchronized methods, then any number of Threads can access the non-synchronized methods in any way they wish without having to wait for someone or something.
The Bottom line here is, Thread T2 doesn't need to wait for Thread T1 to complete its execution as it is trying to execute a non synchronized method. Hope This answer meets your expectations.
I see You have edited your question
P.S. I have tried a test program already, and I see that my understanding is right. I am just wondering if there is any special scenario where this would not work as I explained to the interviewer.
There is no such scenario. The above points should meet your question.
Upvotes: 4