JDK-8300691 - final variables in for loop headers should accept updates

Maurizio Cimadamore maurizio.cimadamore at oracle.com
Mon Oct 21 15:01:18 UTC 2024


On 21/10/2024 15:39, Archie Cobbs wrote:

> 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.

I’m not sure of that. I mean, I “can see” why you’d think that. But in 
which scope does STEP belong? Yes, it belongs to the for loop header - 
but it is executed /after/ the loop. And, in fact, it can even refer to 
variables that would otherwise be DU outside the loop body:

|void m() { int i; for (int j = 0 ; j < 10 ; j = j + i) { i = 1; // if 
this is commented out, error! } } |

So I’m not sure it is a /strict/ generalization :-)

Maurizio

>
> 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.

​
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20241021/c299a44f/attachment.htm>


More information about the amber-dev mailing list