天天看點

在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實作自由通路局部變量是通過通路它的副本而不是它本身。如果本地變量隻被配置設定一次的話,這副本和變量就沒有什麼不同的,是以就有了這個限制。第二,這一限制不鼓勵你使用改變外部變量的典型指令式程式設計模式