Video in progress
Can you serialize a lambda? What are the risks of sending a function over the network in distributed systems?
You can, if the target type is Serializable or you use an intersection cast ((Runnable & Serializable) () -> ...). But a serialized lambda depends on the name of the synthetic method the compiler generated: if the code changes a little or versions differ, deserialization breaks. Captured values travel along too, and Java serialization brings security problems.
📖 Answer
Predicate<Order> rule = (Predicate<Order> & Serializable) o -> o.amount().compareTo(limit) > 0;
On serialization a SerializedLambda is written: which class, which synthetic method (lambda$rules$4), which captured arguments. On deserialization, the receiving side must have the same class and a method with the same name.
What can go wrong:
- Versions: if a new lambda is added to the class, the numbers shift, and an old serialized object binds to a different lambda or fails. The Java spec doesn't guarantee this stability, and the JDK documentation doesn't strongly recommend lambda serialization.
- Captured state: if the lambda captures
this, the whole object (and everything it references) is sent. This is the reason for the famousTask not serializableerror in Spark. - Security: Java native serialization is the classic source of deserialization attacks. Accepting a function from an untrusted source is effectively code execution.
- Language lock-in: the receiver also has to be a JVM and have exactly this code.
Systems like Spark, Flink and Hazelcast do send functions anyway, but they distribute the same jar to all nodes and manage version compatibility themselves. Even then many teams use named static classes instead of lambdas: the name is stable, testable, and what is captured is visible.
Between microservices I send data, not functions: a rule configuration (JSON, a DSL), or a rule name and parameters known to both sides. For example, not the code of a "discount rule" but {"type": "MIN_AMOUNT", "value": 100000}. That's both safer and easier to version.
If a lambda ends up in a cache or a session (a comparator in Spring Session, say), that is usually an accident: when you feel a need for serialization, revisit the design.
Sign up to mark studied questions and save your progress.