在JAVA中为什么本地变量传入内部类中要加final关键字

First,there's a key difference in how instance and local variables are implemented behind the scenes.Instance variables are stored on the heap, whereas local variables live on the stack. If a lambda could access the local variable directly and the lambda were used in a thread, then the thread using the lambda could try to access the variable after the thread that allocated the variable had deallocated it. Hence, Java implements access to a free local variable as access to a copy of it rather than access to the original variable. This makes no difference if the local variable is assigned to only once — hence the restriction.

Second, this restriction also discourages typical imperative programming patterns that mutate an outer variable.

——《java8 in action》


大意:本地变量和实例的实现原理不同。实例变量是存储在堆中的而本地变量是存活在栈中的。如果在一个线程中的lambda(可以理解为一个内部类,下文就用内部类代替这个词)能直接访问这个本地变量,然后在当前分配本地变量这个线程被释放后内部类所在的线程可以试图访问这个变量。因此,Java实现自由访问局部变量是通过访问它的副本而不是它本身。如果本地变量只被分配一次的话,这副本和变量就没有什么不同的,因此就有了这个限制。第二,这一限制不鼓励你使用改变外部变量的典型命令式编程模式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值