IntelliJ Java IDE
The moose likes Threads and Synchronization and the fly likes synchronized block question Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "synchronized block question" Watch "synchronized block question" New topic
Author

synchronized block question

shawn larkin
Ranch Hand

Joined: Feb 04, 2002
Posts: 34
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

Joined: Feb 04, 2002
Posts: 134
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

Joined: Apr 20, 2000
Posts: 3252
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

Joined: Feb 04, 2002
Posts: 34
thank a lot!!! That cleared it up
 
 
subject: synchronized block question
 
Threads others viewed
Synchronize
What is the diff btw these ?
Monitor and lock?
static synchronized block
Thread.yield vs sleep
developer file tools