dcsimg
Critical section: What is the difference between synchronizing the method and synchronizing the instance in a block?
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Dirk_Froehner
Posted On:   Saturday, May 25, 2002 10:10 AM

Hello all, please consider the following two implementations of class foo. I want to make sure that method bar() is not called simultaneously by two threads, because it does some modification on a member. Approach 1) class foo { private Entity myEntity; public synchronized bar() { myEntity.modifiy(); } } Approach 2) class foo { private Entity myEntity; public bar() { synchronized(this) { myEntity.modify(); } } } I know that I can do that with approach 1) and it works fine. Now, I just wanted to try out another way in a   More>>


Hello all,



please consider the following two implementations of class foo. I want to make sure that method bar() is not called simultaneously by two threads, because it does some modification on a member.



Approach 1)


			
class foo {
private Entity myEntity;
public synchronized bar() {
myEntity.modifiy();
}
}


Approach 2)


			
class foo {
private Entity myEntity;
public bar() {
synchronized(this) {
myEntity.modify();
}
}
}


I know that I can do that with approach 1) and it works fine. Now, I just wanted to try out another way in approach 2). I actually expected that the second approach would also be a possible solution, since the first thread that enters the synchronized block acquires the lock on the instance of foo and a second thread has to wait until the first thread leaves the critical section. But it does not work: multiple threads are entering the critical section simultaneously this way. (In my process, there is only one instance of foo, by the way.)



Thanks for any hints.

   <<Less

Re: Critical section: What is the difference between synchronizing the method and synchronizing the instance in a block?

Posted By:   Sundari_Srinivasamurthy  
Posted On:   Monday, May 27, 2002 12:43 AM

Will this help ??



synchronized(myEntity)


{

myEntity.modify();

}

Re: Critical section: What is the difference between synchronizing the method and synchronizing the instance in a block?

Posted By:   Steve_Long  
Posted On:   Saturday, May 25, 2002 04:41 PM

try declaring a static final attribute and using that as the synchronizing item rather than using "this", ie



class foo {
private static final Object lock;
private Entity myEntity;
public bar() {
synchronized (lock) {
myEntity.modify();
}
}
}

About | Sitemap | Contact