JDK-8300691 - final variables in for loop headers should accept updates
Archie Cobbs
archie.cobbs at gmail.com
Mon Oct 21 14:39:03 UTC 2024
On Mon, Oct 21, 2024 at 4:48 AM Maurizio Cimadamore <
maurizio.cimadamore at oracle.com> wrote:
> In other words, to me the crux of the problem remains the definition of
> the loop induction variable. We want to carve out some special rules that
> allow us to treat the loop induction variable *as if* it was a variable
> freshly declared inside the loop body (e.g. meaning that the assignment we
> see in the STEP part of the loop doesn’t really affect whether that
> variable can be captured or not).
>
> That seems kind of an orthogonal extension to the one you are proposing
> here - surely, “effectively frozen” will allow capture for far more locals
> (as your finder experiments show), but we still need to somehow be able to
> special case the treatment for loop induction variables.
>
I'm saying something different from that... and also simpler.
Let's restate the conjecture: Suppose we changed the requirement for lambda
capture of a variable from "final or effectively final" to "final or
effectively frozen at the point of capture", where "effectively frozen at
the point of capture" means there are no mutations to the variable that
lexically follow the capturing lambda.
Then this would clearly subsume what's proposed in JDK-8341785 (basic for()
loop variables are capturable) - it's a strict expansion of that.
So no special treatment of loop induction variables is needed.
Not only that, even though it's broader, it's a much simpler requirement
that has no dependence on DA/DU analysis or any kind of flow analysis.
So I'm saying that this "space" interpretation - which is strictly lexical
- is superior because it has all of the following nice attributes:
- It solves the original problem - allow capture of basic for() loop
variables mutated only in the loop header
- It also solves a much wider set of "dummy variable" cases in other
code (e.g., do and while loops, and all but 5 of the METHODREF examples in
the JDK)
- Yet it still seems to closely match developer intuition - or at least,
no less closely than the previous more limited basic for() loop proposal
does
- It is very simple to specify and understand
The upshot is: If one were to evaluate possible replacements for the "final
or effectively final" requirement for variable capture, in my opinion this
would be a promising option - and in particular has a much higher
cost/benefit ratio than the earlier proposal of just addressing basic for()
loop variables.
-Archie
--
Archie L. Cobbs
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20241021/001c2c4e/attachment-0001.htm>
More information about the amber-dev
mailing list