为什么 lambdas 中的变量必须是最终的或有效的最终? [英] Why does variables in lambdas have to be final or effectively final?

查看:34
本文介绍了为什么 lambdas 中的变量必须是最终的或有效的最终?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我编写这段代码时,我收到一个编译时错误,它说:'lambda 中的变量必须是最终的或有效的最终变量'.

When I am writing this code I am getting a compile time error which says: 'Variables in lambdas must be final or effectively final'.

现在,我知道从行中删除 i :

Now, I get this that removing the i from the line :

futureLists.add(executorService.submit(() -> "Hello world" + i));

解决了这个问题.

但我想知道为什么会有这样的要求?

But I want to know that why does such a requirement exist?

根据 JLS,它说的是:

任何使用但未在 lambda 表达式中声明的局部变量、形式参数或异常参数必须声明为 final 或有效 final,否则在尝试使用时会发生编译时错误.

Any local variable, formal parameter, or exception parameter used but not declared in a lambda expression must either be declared final or be effectively final, or a compile-time error occurs where the use is attempted.

但它没有说明为什么存在这样的要求.但是为什么 Java 工程师要对 lambdas 强制执行这样的要求?

But it does not state, why such a requirement exist. But why did Java engineers enforce such a requirement for lambdas?

public class test {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
         ExecutorService executorService = Executors.newFixedThreadPool(10);

         List<Future<String>> futureLists = new ArrayList<>();

         for (int i = 0; i < 20; i++) {
             futureLists.add(executorService.submit( () -> "Hello world" + i));
             }

         for (Future<String> itr:futureLists) {
             System.out.println(itr.get());
            }
       }
   }

推荐答案

与多线程编程有关.

Java 中的局部变量直到现在都不受竞争条件的影响和可见性问题,因为它们只能被线程访问执行声明它们的方法.但是 lambda 可以是从创建它的线程传递到另一个线程,并且因此,如果 lambda 由第二个线程,被赋予了改变局部变量的能力.- 来源

Local variables in Java have until now been immune to race conditions and visibility problems because they are accessible only to the thread executing the method in which they are declared. But a lambda can be passed from the thread that created it to a different thread, and that immunity would therefore be lost if the lambda, evaluated by the second thread, were given the ability to mutate local variables. - Source

这篇关于为什么 lambdas 中的变量必须是最终的或有效的最终?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆