This example is a simulation of closures in JavaScript (I don't know JS):
public class Lambda {
public static void main(String[] args) {
Supplier generator = Lambda.generator();
System.out.println(generator.get());
System.out.println(generator.get());
System.out.println(generator.get());
}
static Supplier<Integer> generator() {
Integer arr[] = {0};
return () -> ++arr[0];
}
}
The output is 1 2 3.
Usually the lifespan of local method variables is limited by the method execution time. But in this case the reference to arr[]
is stored somewhere. So where is it stored and what's under the hood?