Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

What is the real deal with the use of synchronized  RSS feed

 
Alok Pota
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A lot of authors warn against the perils of synchronizing everything in your classes. Recently I read one of the slides at JavaOne 2000 where it was said that synchronization is not that expensive especially in places where it is needed. There are several clever alternatives to synchronization out there but the JavaOne slide claimed that it is better to go with synchronization then to try any of the clever alternatives.
More specifically, I have a central 'manager' class in which every method is synchronized. In a web based application will that manager class be a bottleneck?.
 
Mark Savory
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If all the methods are synchronized in the 'manager' class then every thread that calls a method on 'manager' must get a lock on 'manager'. You can reduce the bottleneck if you can synchronize on more specific objects that are memebers of 'manager'. Can you?
 
Rahul Rathore
Ranch Hand
Posts: 324
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Even if you have to synchronize every method, you might ensure that the methods do not (in the same thread) do long time-consuming tasks such as executing a long loop, or blocking in doing read/write over the socket. The thread executing the synchronized method of manager must return as quickly as possible, so that it does not hold lock for too long. Such a thread will delegate time-consuming tasks to another thread and return immediately. Also use the wait()-notify() protocol intelligently to ensure that threads do not redundantly and repeatedly try to execute the methods even when the condition is not ripe for their execution.
Mark's idea is also right. But I think it may complicate the design, and leads to the dangers of deadlocks and nested lockouts.

[This message has been edited by Rahul Rathore (edited March 30, 2001).]
 
Sri Bala
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can also consider synchronizing part of the method which will reduce the locking time rather than synchronizing the whole method if possible.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!