In my java project, almost every non-static method I’ve written is synchronized. I’ve decided to fix up some code today, by removing most of the synchronized keywords. Right there I created several threading issues that took quite a while to fix, with no increase in performance. In the end I reverted everything.
I don’t see anyone else writing code with “synchronized” everywhere. So is there any reason I shouldn’t have “synchronized” everywhere?
What if I don’t care too much about performance (ie. the method isn’t called more than once every few seconds)?
Of course – performance. Monitors have a cost.
The answer is neither removing nor adding synchronization in a random fashion. Better to read something like Brian Goetz’ “Java Concurrency In Practice” or Doug Lea’s “Java Threads” books to understand how to do it properly. And learn the new concurrent packages well, of course.
Multithreading is a lot more than the synchronized keyword.