gk wrote:
Hi, i found an reference which says
synchronized void foo() {
/* body */
}
IS EQUIVALENT TO
void foo() {
synchronized (this) {
/* body */
}
}
so, does Synchronizing a method locks the whole object ?
I don't know what you mean by "the whole object". The synchronized
keyword on an instance method synchronizes on the "this" object. The
synchronized keyword on a static method synchronizes on the Class object.
If thats case then...
say, i have a class
class Myclass
{
public void M1()
{
//code
}
synchronized void M2() {
//code
}
}
Now, say ...one thread T1 grabbed M2() ....now, at the same time,
suppose another thread T2 wants to get M1()....is it possible for T2 to
get M1() now or it will be locked ?
There is no locking of methods in Java. All synchronization is
associated with some object. Any thread that is in M2 prevents entry to
any block that is synchronized on the same Myclass instance. It does not
prevent entry to M1, because it is not synchronized on the Myclass instance.
If, on the other hand, M1 contained a block:
synchronized(this){
...
}
that block could not be entered while another thread is executing M2 for
the same Myclass instance.
ok....but if M1 had code like this..