Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Optimizations on synchronized methods in java/C++

3 views
Skip to first unread message

Srikanth Raju

unread,
Jul 20, 2010, 4:35:31 AM7/20/10
to
I was wondering whether any optimizations are automatically done by
the compiler or VM in Java in classes where methods are defined as
synchronized. I'm working with a library where a typical function is
defined so,

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?

Marco van de Voort

unread,
Jul 21, 2010, 7:58:06 AM7/21/10
to
On 2010-07-20, Srikanth Raju <srik...@gmail.com> wrote:
> 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.

Joshua Cranmer

unread,
Jul 21, 2010, 5:53:30 PM7/21/10
to

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

0 new messages