aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes thread doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "thread doubt" Watch "thread doubt" New topic
Author

thread doubt

amit taneja
Ranch Hand

Joined: Mar 14, 2003
Posts: 806
Hi in K&B book its written...

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 ]

Thanks and Regards, Amit Taneja
Saranyan Narayanan
Ranch Hand

Joined: Mar 12, 2003
Posts: 34
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
Edwin Dalorzo
Ranch Hand

Joined: Dec 31, 2004
Posts: 961
Let's see a sample code



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.
soumya ravindranath
Ranch Hand

Joined: Jan 26, 2001
Posts: 300
Hi Amit,

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.

Does that help ?

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: thread doubt
 
Similar Threads
Synchronized methods Vs Synchronized blocks
differences between synchronized blocks and synchronized() method
Sychronization
About synchoronized code blocks in java
Paragraph on threads (K&B)