Re: Optimizations on synchronized methods in java/C++

Joshua Cranmer <Pidgeot18@verizon.invalid>
Wed, 21 Jul 2010 17:53:30 -0400

          From comp.compilers

Related articles
Optimizations on synchronized methods in java/C++ srikiraju@gmail.com (Srikanth Raju) (2010-07-20)
Re: Optimizations on synchronized methods in java/C++ marcov@turtle.stack.nl (Marco van de Voort) (2010-07-21)
Re: Optimizations on synchronized methods in java/C++ Pidgeot18@verizon.invalid (Joshua Cranmer) (2010-07-21)
| List of all articles for this month |

From: Joshua Cranmer <Pidgeot18@verizon.invalid>
Newsgroups: comp.compilers
Date: Wed, 21 Jul 2010 17:53:30 -0400
Organization: Georgia Institute of Technology
References: 10-07-023
Keywords: Java, optimize
Posted-Date: 22 Jul 2010 13:35:39 EDT

On 07/20/2010 04:35 AM, Srikanth Raju wrote:
> 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?


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



Post a followup to this message

Return to the comp.compilers page.
Search the comp.compilers archives again.