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

John Rose john.r.rose at oracle.com
Thu Oct 24 00:21:08 UTC 2024


On 23 Oct 2024, at 14:49, Remi Forax wrote:

>>
> As a teacher, here is the issue most of my student struggle with, they have a code like
>
> for(var i = 0; i < 4; i++) {
> new Thread(() -> {
> ...
> }).start(),
> }
>
> The code can use plain threads, virtual threads, an executor or structured concurrency, etc ... you get the idea.
>
> Then they want to access to induction variable 'i' inside the lambda.
>
> At that point, some students knows how to fix the issue using another local variable in the body of the loop but others start to become "creative",
> - some are using IntStream.range().forEach(i -> ) but usually, it fails because it's quite usual for this kind of code to have also a method call that throws a checked exception (Thread.sleep(), object.wait(), thread.join(), future.get(), etc)
> - some try to write their own range() method using an "enhanced for" like Tagir said, here are the usual examples
> - for(var i : List.of(0, 1, 2, 3)) {
> - for(var i : IntStream.range(0, 4).boxed().toList()) {
> - for(var i : new int[] { 0, 1, 2, 3 }) {
> - for(var i : (Iterable<Integer>) IntStream.range(0, 4)::iterator) { // those students have read Effective Java

Wow.  Each of those is personally familiar to me as well, as I tried to force new-for into a mold that was just slightly the wrong shape.  While old-for has the right shape for this, according to long custom.  Yuck.

It reminds me of the story that ends “with all this manure there’s got to be a pony in here somewhere”.  Let’s give the kid his pony.

> For me, allowing my students to capture the induction variable of simple for loops so they can focus on the rest of the code is a win.

Yes.  It could happen every time a learner sets out to make N threads, each doing something for some i<N.  It happened to me (although I wasn’t a beginner at the time).  From one perspective it’s a “Java onramp” issue:  It tends to happen the first time a programmer combines a numeric for loop with threads.


More information about the amber-dev mailing list