Originally posted by Lucas Lee: In general, sychronized block will block less scope,and will present better performance.
I think Earnest was comparing a synchronised method with an unsynchronised method whose whole content was inside a synchronized(this). In that case, there is absolutely no difference between the two.
On the other hand, if only part of the content of the method needs to be protected by synchronisation, then one generally should protect only that part, allowing the rest of the code to execute freely. Depending on what the rest of the code does, that may or may not save significant time.
Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Common sense tells us that a synchronized method should be exactly equivalent to a synchronized block coverint the entire body of the method. However, common sense doesn't always apply. Most compilers (from Sun at least) will compile a synchronized block differently than a synchronized method, resulting in different bytecodes. And in fact the perfomance of each one may be slightly different. I ran tests showing that the method with a synchronized block ran about 4% slower on my machine than an synchronized method, with uncontested synchronization and nothing in the loop other than testing the synchronization. Different machines may yield different results of course - and I'd say the difference is almost always irrelevant. If there's any lock contention, or any remotely interesting work to be done by the method, the difference in performance should be even smaller. I do recall that on some older JVMs this difference was more pronounced, but as modern JVMs hav eimplemented faster synchronization, they seem to have also shrunk the disparity between these two techniques.
As a practical matter, the fact that the synchronized block is more flexible in terms of scope and in terms of choosing a monitor is much more important than the miniscule perfarmance difference that may exist here. Also, I like the fact that synchronized blocks force the user to specify just what object they're using as a monitor. Java's decision to implicitly synchronize on "this" for instance methods has led to a large number of developers who have little or no idea how to use a monitor, and don't pay attention when there's more than one potential monitor present. Explicitly specifying a monitor may look slightly more cumbersome, but it's a good thing, in my opinion.