• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

synchronizatoin problem

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Why is the word "abbreviation" so long? And this ad is so short?
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic