This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
When you synchronize a method, the object used to invoke the method is the object whose lock must be acquired. But when you synchronize a block of code, you specify which object’s lock you want to use as the lock, so you could, for example, use some third-party object as the lock for this piece of code. That gives you the ability to have more than one lock for code synchronization within a single object
i didn't understand what above para means....
pls explain [ April 22, 2005: Message edited by: amit taneja ]
Method synchronization is on the object (this) Synchronization blocks are on a certain object --> can be (this), meaning current object , or some object on which you need synchronization to avoid concurrent access from multiple threads leading to data corruption in the objects
This is a synchronized method. That means that only one thread at the time can execute the code of the method. To gain access to the method, the thread must obtain a lock on the object. So the code would be very similar to this:
Now, you could use another object, different from this, to obtain a lock (that's to say, the right to execute the code withing the synchronized block.
It has the another adventage: you can control better the scope of the synchronization and therefore possibly optimizing performance.
Lifted some code from another of our threads (!) -
In the following code, you can see that ThreadA creates an instance of ThreadB class and then synchronizes on the object b. This is what is meant by synchronized(anotherObject) in a block of code. When you do this, you have sole access to the object b and can work on it without allowing other threads to access b. ThreadB's run() has synchronized(this), meaning that while ThreadB executes that block of code, no other thread can lay hands on that instance of ThreadB.