RFR: 8341782: Allow lambda capture of basic for() loop variables as with enhanced for() [v2]
Archie Cobbs
acobbs at openjdk.org
Thu Oct 10 23:45:45 UTC 2024
On Thu, 10 Oct 2024 17:50:43 GMT, Archie Cobbs <acobbs at openjdk.org> wrote:
>>> An example that would then be allowed:
>>>
>>> ```java
>>> int i, j = 0;
>>> while (true) {
>>> j += i;
>>> {
>>> Runnable action = () -> foo(i + j);
>>> try {
>>> this.executor.submit(action).get();
>>> } catch (InterruptedException e) {
>>> break;
>>> }
>>> }
>>> i++;
>>> }
>>> ```
>>
>> I tend to agree with this line of thinking. And this is IMHO, a sign that the design has not yet fully settled. The main thing to notice is that there's two stable design points:
>> 1. only capture effectively final vars (where the language is today);
>> 2. capture every variable - with the understanding that what's being captured is the _current_ value (and not a "mutable box" which keeps changing in real time - that would be awful).
>>
>> Having special rules for loop variables is sending us down the slippery slope of finding the next stable point between (1) and (2) - assuming one exists. The risk here is that once we start relaxing things in some areas (e.g. loops) you can quickly run into issues where other deficiencies in capture become even more apparent.
>
>> Having special rules for loop variables is sending us down the slippery slope of finding the next stable point between (1) and (2) - assuming one exists. The risk here is that once we start relaxing things in some areas (e.g. loops) you can quickly run into issues where other deficiencies in capture become even more apparent.
>
> I agree with all of that as well. There is one valid counter-argument though (reflected in the JEP draft) which is that we have already taken this current step with enhanced `for()` loops, so we're not really establishing any much of a new "frontier" with this feature by adding the same thing to basic `for()`. In other words, enhanced `for()` is an intermediate design point that's already been taken, for better or worse, so we might as well make the most of it. Or put more plaintively, "Please don't blame this feature for all the world's problems" :)
>
> Regarding the bigger picture question, I'm skeptical that there exists any other design point between 1 and 2 that would be preferable to just jumping straight to 2, i.e., capture anything that's DA anywhere, but of course anything's possible.
Thanks for the bug fix suggestion. Should be fixed in 00181f7f1b4.
-------------
PR Review Comment: https://git.openjdk.org/jdk/pull/21415#discussion_r1796228126
More information about the compiler-dev
mailing list