• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

locking an object other than this

 
sai donthneni
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when do you use this kind of synchronization

synchronized(mutex)
{
//
}

mutex represents the object whose object level lock should be acquired before entering the lock.
 
Edwin Dalorzo
Ranch Hand
Posts: 961
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you synchronize a whole method like this...



...you know that no other thread will ever get to execute this code if the lock is already acquired by one thread.

Hence, if you want to decrease the scope of the lock, letting other threads to execute part of method, you can better control the scope of the lock by means of using synchronized blocks. Like this...



This way you may gain some performance by means of reducing the scope of the lock.

Also, the new concurrent package in Java Tiger (JSE 1.5) will offer you even more control over the locking system. You might like to give it a look at java.util.concurrent API.

Regards,
Edwin Dalorzo
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic