A final variable doesn’t mean immutable or thread safe for Classes in Java. You are still on your own unless the class was written in an immutable/thread-safe way (like the String class).
I think that the more important reason is that it would be able to capture and somehow observe the changes to stack-allocated variables, which can go out of scope. Even though memory management is not specified in JLS, this would be a huge pain in the ass to implement.
You can do this in C#. The compiler automatically makes the captured local variable a field in an anonymous class. The local variable stops being a local variable even before it is captured.
Allowing mutable multi threaded access always requires locks to work correctly. So the only alternative would have been to introduce implicit locking on those variables. Which is unflexibel and takes away control. The only thing I would change is that the error when capturing mutating variables would suggest using locks such as mutex or rw lock.
effective final - i dont know if that is as protective as you claim since the objects can still be wrongly modified as there is no real const final (yet)
By that logic, Java should also prevent sharing all mutable variables across threads because that also can lead to race conditions. Which, by the way, what do you mean by "something that does not exist in Java"?????
Great reel!
good to know thanks
This is not a great design choice imo. Many times I had to declare a variable as a one sized array or into an atomic reference just to use it in lambdas. It should either be implicit or a deeper change
Ahahahha, except volatile! And, of course, a supplier.
But at some point in the Java history this rule has been relaxed to only requiring that the captured variable must be "effectively final", meaning it doesn't change within in its scope and lifetime, in which case there is no need for declaring it to be final explicitly. So the following code compiles and prints the expected answer in Java 21: ``` import java.util.function.*; public class Main { public static void main(String[] args) { System.out.println( times6().apply(7) ); } static Function<Integer, Integer> times6() { int m = 6; // m is effectively final return n -> n * m; } } ```
Great example, returning a lambda in a method with return type void :D good video anyways, as well
Yeah, but you still can screw things up using non thread safe modifiable collections
Because under the hood each lambda is a class with primitive final fields
cotcurret
Bro speaks French in English
That's just a cop out
Race conditions absolutely exist in Java. I think he didn’t drink his coffee before this one 😂
Actually this problem always exists to the one uses Ai prompt and that includes me that's why I usually refactor it again after copying the code from Ai
N/A