class Foo
{
private int a = 0;
private int b = 0;
public synchronized doSomethingWithA( int var )
{
int tmp = some_function( var ); // heavy computation
a += tmp;
}
public synchronized doSomethingWithB( int var )
{
int tmp = some_function( var ); // heavy computation
b += tmp;
}
};
Can the compiler see that the first statement in the methods are local
and therefore not lock the object for that statement, and hold the
lock only for the actual addition part, so that it saves time?
I'm no Java expert, but looking at this piece of code, not the state is
flagged as synchronized, but the method, so I don't see how the compiler
could see it is all about "a" and "b" in the first place.
some_function could theoretically have side effects that rely on the
guarantees of the synchronized, even if it never used the Foo class. The
use of the synchronized keyword on the function is that the programmer
intends for the entire function call to be within the critical section;
otherwise, just the interesting statements could be protected.
In short: such an optimization would be dangerous (and expensive if not
impossible to see if it is safe!), and it is not only easy but
recommended to achieve the same ultimate effect by other means.
--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth