Welcome Message

Hi, welcome to my website. This is a place where you can get all the questions, puzzles, algorithms asked in interviews and their solutions. Feel free to contact me if you have any queries / suggestions and please leave your valuable comments.. Thanks for visiting -Pragya.

December 25, 2009

Class level and Object level locks -- V.Imp.

Remember what we're talking about is multi-threading. It doesn't matter in which objects we do the invoking of methods, but which threads all those objects are executing in when the invocation is done (and since execution in a single thread is sequential, we cannot invoke the same method twice simultaneously in a single thread, unless we're using recursion).

I think it's easiest to work through this with a simple example. Let's take one class with one synchronized instance method:
view plaincopy to clipboardprint?
public class ClassA {
public synchronized void mymethod() {}
}
and also declare a couple of instances of this class I1 and I2 say. We also have three threads around and running - let's call them T1, T2 and T3.

Now, suppose within thread T1 we invoke I1.mymethod() at some point in time. Then until this invocation returns, T2 and T3 are locked out of calling I1.mymethod(). However, one of those threads may still invoke I2.mymethod() without blocking since that's a different object (albeit of the same class). Once I1.mymethod() returns, any of the threads may again invoke that method on that object. Similarly, once I2.mymethod() returns, any of the threads may invoke that method.

I think you may have understood, but it was unclear when you were referring to different classes instead of instances of the same class. Your example was correct: if we have several different classes, then we can apply the same logic as above if I1 is an instance of ClassA, I2 of ClassB and a third instance I3 of ClassC, but it's probably less obvious to consider the case where they are all of the same class first.

Now, if we make the method static:
view plaincopy to clipboardprint?
public class ClassA {
public static synchronized void mymethod();
}
then the previous explanation will fail since the lock is now a class lock so holds on all static methods of all instances of ClassA simultaneously. An invocation of I1.mymethod() from thread T1 will now lock threads T2 and T3 from calling any occurrences of any static methods on any other instances of ClassA. However, since it's a class lock, it won't block any invocations of static methods from other classes (i.e. classes other than ClassA), nor will it block invocations of instance methods.

http://www.coderanch.com/t/416338/Threads-Synchronization/java/Accesing-two-synchronized-methods

No comments: