@backstreetbrogrammer
--------------------------------------------------------------------------------
Chapter 16 - Spark RDD - Closures and Shared Variables
--------------------------------------------------------------------------------
A closure is an instance of a function that can reference non-local variables of that function with no restrictions.
For example, a closure could be passed as argument to another function. It could also access and modify variables defined outside its scope.
- Understanding closure concept in Java
Java lambdas and anonymous classes do something similar to closures: they can be passed as argument to methods and can access variables outside their scope.
But they have a restriction: they can’t modify the content of local variables of a method in which the lambda is defined. Those variables have to be final or effectively final. It helps to think that lambdas close over values rather than variables.
This restriction exists because local variables live on the stack and are implicitly confined to the thread they’re in. Allowing capture of mutable local variables opens new thread unsafe possibilities, which are undesirable (instance variables are fine because they live on the heap, which is shared across threads).
Example:
Following code will NOT compile as String name variable is not final or effectively final:
String name = "John";
Runnable r = () -: System.out.println(name); // WILL NOT COMPILE
name = "Betty";
Github: github.com/backstreetbrogramm...
- Apache Spark for Java Developers Playlist: • Apache Spark for Java ...
- Upgrade to Java 21 Playlist: • Upgrade to Java 21
- Top Java Coding Interview Problems Playlist: • Top Java Coding Interv...
- Java Serialization Playlist: • Java Serialization
- Dynamic Programming Playlist: • Dynamic Programming
#java #javadevelopers #javaprogramming #apachespark #spark
Негізгі бет Ғылым және технология 77 - Spark RDD - Closures and Shared Variables
Пікірлер