This week's book giveaway is in the JavaScript forum.
We're giving away four copies of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js and have Paul Jensen on-line!
See this thread for details.
Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Synchronization should be avoided.  RSS feed

 
Meenu Mehta
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am new to using threads. I have read in many articles that synchronization makes the programs slow and un-neccessary synchronization should be avoided. Can you please tell me why synchronized methods take longer time and what can be the harm of using it more.

Thanks,
Meenu
 
Henry Wong
author
Sheriff
Posts: 23275
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Meenu Mehta:
Hi,

I am new to using threads. I have read in many articles that synchronization makes the programs slow and un-neccessary synchronization should be avoided. Can you please tell me why synchronized methods take longer time and what can be the harm of using it more.

Thanks,
Meenu


Well... it is not that clearly black and white.

On one side... of course, un-necessary synchronizations are bad. It takes time to grab the lock, which is much slower than say, *not* grabbing the lock...

And while holding the lock, you are effective "single threaded" with other code that also need the lock. If it is not necessary, then you are forcing threads to needlessly wait.

On the other side... Threads are complicated. And race conditions are very difficult to track down. Just because something is not showing up in the test environment doesn't mean that it won't show up in production. Never ever depend on a behavior of a race condition -- either allow all cases to happen, or make it thread safe.

Also, just because a class will not be used by multiple threads now, doesn't mean it won't be in the future. It may be better to make life easier in the future by making classes thread safe now.

Henry
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
People tell you to avoid synchronization the same way they tell you to conserve energy. It doesn't mean never to use a car or cook your food or heat your home -- it just means to do so wisely. Don't make every method synchronized in the same way that you don't leave your car running overnight, just in case you need to go somewhere.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!