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