Re: JavaMemoryModel: FWD: Question regarding nested synchronized blocks

From: Bill Pugh (pugh@cs.umd.edu)
Date: Mon Apr 22 2002 - 19:31:23 EDT


Paul,
   Note that the Java memory model is currently being revised. Don't
bother paying attention to the existing chapter 17 except as a
historical curiosity.

>[ Forwarded from "Jack, Paul" <pjack@sfaf.org>; who isn't subscribed
>via that email address]
>I read in a JavaWorld article that it's forbidden
>for two synchronized blocks to be merged:
>
> sychronized (lock) {
> <op1>;
> <op2>;
> }
> synchronized (lock) {
> <op3>;
> <op4>;
> }
>
>Now assuming there's no side-effects, an optimizing
>compiler can legally reorder <op1> and <op2>, or
>reorder <op3> and <op4>, but it can't, for instance,
>put <op3> between <op1> and <op2>. This all makes
>sense to me.

Under the new memory model, you will be able to merge synchronization
blocks (although there are fairness issues associated with doing so).
If the synchronization blocks are fused so that no other thread can
obtain the lock between the two synchronization blocks above, then
<op1>, <op2>, <op3> and <op4> can be freely reordered.

>
>My question involves nested sychronized blocks.
>According to the JLS (17.9), "Any association between
>locks and variables is purely conventional. Locking
>*any* lock conceptually flushes *all* variables from a
>thread's working memory..."
>
>So given nested locks...
>
> synchronized (lock1) {
> synchronized (lock2) {
> <op1>;
> <op2>;
> }
> <op3>;
> <op4>;
> <op5>;
> synchronized (lock2) {
> <op6>;
> <op7>;
> }
> }
>
>...what reorderings are allowed? It seems that
><op2><op1> <op5><op4><op3> <op7><op6> would
>be legal, but not <op4> <op2><op1> <op5>
><op7><op6> <op3>. Am I correct in this assumption,
>and if I am, what's the rationale?

You are correct with regards to the old memory model.

However, under the new memory model, this restriction is being
removed (because there was no rationale).

        Bill
-------------------------------
JavaMemoryModel mailing list - http://www.cs.umd.edu/~pugh/java/memoryModel



This archive was generated by hypermail 2b29 : Thu Oct 13 2005 - 07:00:39 EDT