• Post Reply Bookmark Topic Watch Topic
  • New Topic

synchronized block question  RSS feed

 
shawn larkin
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a question about the object that is used as a param of the synchronized block:
synchronized(object) <------
I understand that the Thread claims the monitor of that object, but since that object doesn't have to be used in the synchronized block:
synchronized(object1)
{
return object2;
}
what is the point of using that object? What does it do, when you claim the monitor of an object that's not actually being used in that block? I could find a good answer in any of my books? And I haven't encountered anything else in Java to compare it to.
Thanks in advance.
 
Mehul Sanghvi
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi...
Every logical block of synchronized methods/blocks requires someone to guard it against more than one thread accessing the logical block at the same time.
Hence each logical block requires a "watchman", it is not necessary that this watchman have to play any role during the execution of the block which it is guarding... its job is just to see that only one thread at a time is allowed inside the block which it is guarding. This funtionality of "Monitoring" is bestowed to any type of object...
I hope I am clear enough to answere your doubt.
Regards,
Mehul.....
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Usually, you do use the object you are synchronizing on within the block. A good example would be when you have a (synchronized) Collection and you want to iterate over it - you have to synchronize on the Collection before you call iterator() and must not let go until you have finished iterating, i.e. the entire operation needs to take place inside a block synchronized on the Collection.
Sometimes however there isn't an obvious object to synchronize on. Then it can be best to create a special monitor object (just a new Object()) specifically for the purpose. See the source for java.io.File for a good example - there are a number of different operations protected by a monitor Object called "tmpFileLock".
There are a number of other places in the JDK where objects are used in this way.
- Peter
[ February 05, 2002: Message edited by: Peter den Haan ]
 
shawn larkin
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank a lot!!! That cleared it up
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!