dcsimg
What is actually 'locked' during Method Synchronization
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   John_Senford
Posted On:   Monday, June 24, 2002 03:31 AM

I have a class with various sunchronized methods. A Thread enters one of the synchronized methods in which it is made to wait() for a while. Another Thread comes along and calls one of the other synchronized methods but is suspended at the very beginning of this method until the waiting Thread above finishes waiting and returns from that synchronized method. The two methods in question do NOT reference any of the SAME class/instance variables (which I originally expected to be causing the contension). Based upon the above behavour, I am left a little confused as to what is actually happening when a method is declared as being 'synchronized'. Could anybody enlighten me..   More>>

I have a class with various sunchronized methods.


A Thread enters one of the synchronized methods in which it is made to wait() for a while.


Another Thread comes along and calls one of the other synchronized methods but is suspended at the very beginning of this method until the waiting Thread above finishes waiting and returns from that synchronized method.


The two methods in question do NOT reference any of the SAME class/instance variables (which I originally expected to be causing the contension).


Based upon the above behavour, I am left a little confused as to what is actually happening when a method is declared as being 'synchronized'.

Could anybody enlighten me....?


What I hoped is that synchronizing an entire method would basically have the same effect as synchronizing each of the class/instance variables referenced from within that method.

   <<Less

Re: What is actually 'locked' during Method Synchronization

Posted By:   Mike_Friedrich  
Posted On:   Tuesday, July 16, 2002 02:32 PM

The synchronization works on this object of the method (on the class-object for static methods).


This ...


class A {
int x;
int y;
synchronized void m1() {
x=0;
}
synchronized void m2() {
y=0;
}
}


... works like:

class A {
int x;
int y;
void m1() {
synchronized(this) {
x=0;
}
}
void m2() {
synchronized(this) {
y=0;
}
}
}


It does not matter what is inside of the methods.

If you need a fine-grained controll, you can use synchronized on an hidden/dummy object (a class-member).


Regards, Mike

(I don't know if this is realy answered here already.)

Re: What is actually 'locked' during Method Synchronization

Posted By:   Stephen_Welch  
Posted On:   Monday, June 24, 2002 04:33 AM

The thread obtains a monitor (lock) on the object. Therefore no other thread can obtain a lock until the owning thread releases it.
About | Sitemap | Contact