Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Clarification On Threads/Synchronization  RSS feed

 
David Harrigan
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hiya,
Still getting my head around something.
When a method (or code block) is declared as synchronized, then when that method (or code block) is executed and the lock is avaiable, then the lock is taken and, here's the bit, *no other synchronized methods or cb's can be called on that object until the lock is released? (i.e., using a wait() or yield())?*
i.e.,
synchronized void method1() {}
synchronized void method2() {}
If a thread enters method1 then all other threads are prevented from accessing not only method1 but also method2 ???
TIA...
David Harrigan.
 
Jerry Pulley
Ranch Hand
Posts: 221
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
David,
That's mostly true. When a thread enters method1, it takes the lock of the object that contains the methods. Since method1 and method2 are synchronized on the same object, code trying to execute method2 will have to wait until that lock becomes available.
The only problem with what you said is the part about yield(). This method does not relinquish any locks.
Jerry
 
David Harrigan
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is wait() the only method that gives up the lock on an object?
 
Jerry Pulley
Ranch Hand
Posts: 221
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
David,
Yes, <code>wait()</code> and its timed variants are the only methods that cause a thread to give up its locks (except for deprecated <code>stop</code>). Of course, a thread also gives up the lock when it leaves the critical section. This diagram that I made up when I was studying threads may help.
Jerry
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!