• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

method Vs block lever synchronization.KATHY I NEED UR COMMENTS TOO

 
Tausif Khanooni
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am reading Kathy's book, chapter "Threads". The para written below is not clear. can any one help me out understanding this??
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 pice of code. That gives you the ability to have more than one lock for code synchronization within a single object.

Is there any difference between method synchronization and block synchronization. This question is very important, because this question is being asked frequently in interviews :roll: .
[ March 18, 2003: Message edited by: Tausif Khanooni ]
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static methods synchronize on the Class.
Non-static methods synchronize on the object that the method is in.
Blocks synchronize on any object you like.
From another thread:
Suppose you have several blocks of code in different methods in your class that you want to synchronize but not with each other. In other words, if you are in block1, I don't want anyone else in block1 but I don't care about someone else going into block2. If I synchronize on (this) the two blocks will be co-synchronized. A thread in one blocks the other. So instead I create two sempahore objects and use them. For example.
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As always, great reply, Tom.
A key point here is to realize that, when you define a method to be synchronized, the JVM automatically assumes that you want to lock on that object when the method is invoked. Therefore, is a process invokes a synchronized method of an object, no other process may invoke a synchronized object until the first process has finished and released the lock.
However, when you have a synchronized block (a bit of code contained within a method, not the entire method), you get to pick which object you want to synchronize on. In other words, you get to pick your semaphore.
You can choose to use 'this', if you'd like, making this lock equivalent to any synchronized methods. However, you can lock on any other object as well. If you choose to lock on some other object, one process could be within the synchronized block while another is in the synchronized block, like this:

I hope that helps,
Corey
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic