capturing (or not) mutable local variables

Doug Lea dl at cs.oswego.edu
Fri Nov 26 04:45:57 PST 2010


On 11/26/10 05:58, Doug Lea wrote:
> However, perhaps the folks arguing for more flexible
> usage could discover more powerful yet practical techniques
> that would still preserve the shallow data-race freedom
> property in more cases, and thus allow some of their target usages.
>

One way is to simply preserve this property, period:
Suppose the translation mechanics for mutable
variables were in terms of ThreadLocal boxed objects, rather
than those possibly shared across threads.

In other words
   class C {
     void f() {
        int i = 0;
         ... #{ ... ++i; ... }
      }
   }

becomes translated to something like:
   class C {
     void f() {
        ThreadLocal<MutableInt> ti = ...;
         ... #{ ... ti.increment(); ... }
      }
   }


It would be challenging to come up good rules to maximize
chances that this is done only when people really meant to
do it. The various "mistake" cases (like for-loop indices)
seem to outnumber the intentional ones.
And further to teach front-end compilers, AOT bytecode
optimizers, and/or JITs to understand these constructions well
enough to avoid all the overhead when it is statically
determinable that lambda can be inlined/macro-expanded in a
way that allows variables to just remain as locals.
It would also provide some fodder for pushing ThreadLocal
support deeper into the language/compilers/runtimes to
help improve performance.

And the net impact on constructions like accumulators
in parallel loops would be that you'd always get a safe
but wrong answer.

All in all, while this may be the best possible compromise
(providing both mutability and guaranteed locality), I
don't see a good reason to do it. However, it does suggest
that if there were better syntax support for safe
workarounds, people might be happier to use them.
Maybe @ThreadLocal could trigger this transformation?

   class C {
     void f() {
        @ThreadLocal int i = 0;
         ... #{ ... ++i; ... }
      }
   }

-Doug


More information about the lambda-dev mailing list