Re: synchronization question
gk wrote On 11/07/06 11:15,:
Hi, i found an reference which says
synchronized void foo() {
/* body */
}
IS EQUIVALENT TO
void foo() {
synchronized (this) {
/* body */
}
}
Pretty much, yes. The generated bytecode may be a little
bit different, but the practical effect is the same.
so, does Synchronizing a method locks the whole object ?
Yes. Or no. Or, well, it depends what you mean.
When you synchronize on some object, Java guarantees
that no other thread can synchronize on that object at the
same time. That is *all* that Java guarantees (aside from
some esoteric but important points about memory visibility
and such). In particular, Java does not guarantee that the
object somehow becomes inaccessible to other threads: they
can still have references to it and they can still use those
references to get at the accessible fields and methods. The
only thing they cannot do is acquire the lock at the same
time you're holding it.
Therefore, "holding the lock" on an object means only
what the class' code says it means. If the class provides
a mixture of synchronized and unsynchronized methods, when
thread T1 synchronizes on the object it prevents T2 from
executing any of the synchronized methods, but T2 can still
use the unsynchronized methods without hindrance. In that
sense, synchronizing does not "lock the whole object."
On the other hand, each Java object has one and only one
lock; there is not a way to synchronize on just a part of
an object. In this sense, synchronization "locks the whole
object;" there's no "partial synchrony." (You can, of course,
choose to synchronize on the sub-objects that your target object
refers to, but then you have synchronized on those other
objects and not on the target object at all. From the point
of view of one single object, its lock is either held or not
held and there are no in-between states.)
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 ?
M1 is not synchronized, so T2 can execute it even if T1
holds the object's lock.
Also, both T1 and T2 can execute M2 simultaneously on
different instances of Myclass: each Myclass instance has its
own lock, independent of any other locks.
--
Eric.Sosman@sun.com