• Post Reply Bookmark Topic Watch Topic
  • New Topic

synchronizatoin problem

 
Vijay Krishna
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I have a doubt regarding thread synchronization. Please have a look
at the following code.

void testMethod(int x){

// some code here....
synchronized(this){
// var is an instance variable
var = x;
// some code here..
this.wait();
// some more code..

}// end of synchronized block

} // end of test method

Suppose 2 threads are trying to execute this code. Fisrt thread enters into
the synchronized block and it will assign a value to the variable var. Now the wait() method is executed, and first thread goes into the wait state, after releasing the lock. So second thread will enter into the synchronized block and changes the variable var. The change made by first thread is now lost.

If this is true, how the synchronization is maintained?

Thanks & Regards,
Vijay
 
Olaf Kummer
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is the intended behavior. Use wait() when you want other threads to change the state of the guarded variables. When you want to wait for an unrelated condition, synchronize and wait on a separate object. Note that you will have to steer around deadlocks carefully in this case.

Olaf
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!