On Jan 27, 12:07 pm, Ashutosh Chauhan <
hashut...@apache.org> wrote:
> I have been told that:
>
> 1) If you unnecessarily synchronize your method where there wasn't a
> need of it. You still won't pay a performance penalty, because JIT
> compiler can detect that there are no way two threads can mangle each
> other in runtime and will avoid locks altogether if it can determine
> it is safe to do so. Assembly code it is emitting at that time will be
> lock free.
This can happen only in certain circumstances. (Google 'escape
analysis' and 'lock elision' for more.) Suppose you have a class Foo
with method bar() that is synchronized.
void someMethod() {
new Foo().bar();
}
The compiler can (in theory) detect that the reference to your new Foo
instance does not escape someMethod() (assuming that Foo's constructor
doesn't leak 'this', etc). It can then remove the locking when calling
bar().
>
> 2) If you unnecessarily synchronize your method, few of javac compiler
> optimizations break at compile time (because of static analysis it
> does) and it wont be able to generate optimized byte code.
The javac compiler does no optimizations anymore. There is a switch do
enable optimizations but it's been ignored since Java 1.4 or so.
>
> Both of these statements are at odds with each other and both may
> still hold (assuming assertions are true) because one happens at
> compile time and another at runtime.
>
> Apart from the correctness first argument of always synchronize when
> in doubt, whats the usual wisdom from performance point of view for
> uncontested locks?
>
> Ashutosh
Uncontested locks are pretty cheap. I don't remember the numbers
exactly but unless you're calling a synchronized method in a hot loop
it's unlikely that locking overhead will be significant compared to,
say, I/O.