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

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

问题描述

当我编写这段代码时,我收到一个编译时错误,上面写着:
'lambdas中的变量必须是最终的或有效的最终'

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被赋予该能力,则
免疫力将因此而丢失改变局部变量。 - 来源

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

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