Serialization of Lambda Expression in Java
Here we will be discussing serialization in java and the problems related to the lambda function without the serialization alongside discussing some ways due to which we require serialization alongside proper implementation as in clean java programs with complete serialization and deserialization process using the function interface.
Serialization is a process for writing the state of an object into a byte stream so that we can transfer it over the network. We can serialize a lambda expression if its target type and its captured arguments have serialized. However, like inner classes, the serialization of lambda expressions is strongly discouraged. As the lambda function is not serialized by default we simply have to cast our lambda to java.io.Serializable. But the submit method requires a Runnable or Callable as the parameter, not a Serializable. So, we have to cast the lambda to two interfaces at the same time Runnable and Serializable.Java Serialization is a good generalized, backwardly compatible serialization library. Two of the most common problems that alternatives try to solve are performance and cross-platform serialization. By comparison, a straightforward binary YAML serialization uses 348, with more options to optimize the serialization. This raises the problem of how to serialize a lambda using an alternative, or cross-platform or faster serialization format.
Note: There occurs a necessity to serialize a lambda function because Serializing lambdas can be useful in a number of use cases such as persisting configuration, or as a visitor pattern to remote resources.
Illustration: Remote visitor
Say We want to access a resource on a remote Map. We can use get/put, but say we just want to return a field from the value of a Map: we can pass a lambda as a visitor to extract the information we want. As you can see, it is easy to add various simple functions, or call a method to perform the action you need. The only problem is that lambdas by default are not serializable.
Example
MapView userMap = Chassis.acquireMap("users", String.class, UserInfo.class); userMap.put("userid", new UserInfo("User's Name")); // Print out changes userInfo.registerSubscriber(System.out::println); // Obtain just the fullName without downloading the whole object String name= userMap.applyToKey("userid", u -> u.fullName); // Increment a counter atomically and trigger // an updated event printed with the subscriber. userMap.asyncUpdateKey("userid", ui -> { ui.usageCounter++; return ui; }); // Incrementing counter and return the userid int count = userMap.syncUpdateKey("userid", ui -> { ui.usageCounter++; return ui;}, ui -> ui.usageCounter);
SerializedLambda class is used by compilers and libraries to ensure that lambdas deserialize correctly. Making the intersection cast of Function<String, String> & Serializable changes the underlying type of the lambda, allowing a library like Kryo to properly understand how to deserialize lambdas given to it.
Adding this extra casting of & Serializable is one possible solution to allow Kryo to deserialize lambdas. An alternative route involves creating a new interface that extends both the underlying Function type that you need, along with Serializable.
Layout:
public class IntersectionCasting { public static void main(String[] args) { SerializableLambda function = (message) -> "Kryo please serialize this message '" + message + "'"; } interface SerializableLambda extends Function<String, String>, Serializable {} }
Now in order to make Lambdas Serializable in our API keeping foremost a thing safe that unfortunately the standard APIs cannot be changed or sub-classes to add this but if you have your own API, you can use a Serializable interface. The user of your API doesn’t have to explicitly say that the lambda is serializable. The remote implementation serializes the lambda, executes it on the server,, and returns the result. Similarly, there are methods for applying a lambda to the map as a whole.
Example:
Java
// Java Program to serialize and deserialize the lambda // function using a function interface // Importing input output classes import java.io.*; // Importing all function utility classes import java.util.function.*; // Interface interface MyInterface { // Method inside this interface void hello(String name); } // Class 1 // Helper class implementing above interface class MyImpl implements MyInterface { // Method of this class public void hello(String name) { System.out.println( "Hello " + name); } } // Class 2 // Main class class GFG { // Method 1 // To Serialize private static void serialize(Serializable obj, String outputPath) throws IOException { File outputFile = new File(outputPath); if (!outputFile.exists()) { outputFile.createNewFile(); } try (ObjectOutputStream outputStream = new ObjectOutputStream( new FileOutputStream(outputFile))) { outputStream.writeObject(obj); } } // Method 2 // To Deserialize private static Object deserialize(String inputPath) throws IOException, ClassNotFoundException { File inputFile = new File(inputPath); try (ObjectInputStream inputStream = new ObjectInputStream( new FileInputStream(inputFile))) { return inputStream.readObject(); } } // Method 3 // To Serialize and deserialize lambda functions private static void serializeAndDeserializeFunction() throws Exception { Function<Integer, String> fn = (Function<Integer, String> & Serializable)(n) -> "Hello " + n; System.out.println( "Run original function: " + fn.apply( 10 )); String path = "./serialized-fn" ; serialize((Serializable)fn, path); System.out.println( "Serialized function to " + path); Function<Integer, String> deserializedFn = (Function<Integer, String>)deserialize(path); System.out.println( "Deserialized function from " + path); System.out.println( "Run deserialized function: " + deserializedFn.apply( 11 )); } // Method 4 // To Serialize and deserialize lambda classes private static void serializeAndDeserializeClass() throws Exception { String path = "./serialized-class" ; serialize(MyImpl. class , path); System.out.println( "Serialized class to " + path); // Pretending we don't know the exact class of the // serialized bits, create an instance from the // class and use it through the interface. Class<?> myImplClass = (Class<?>)deserialize(path); System.out.println( "Deserialized class from " + path); MyInterface instance = (MyInterface)myImplClass.newInstance(); instance.hello( "Java" ); } // Method 5 // Main driver method public static void main(String[] args) throws Exception { // Calling above method 3 and method 4 // in the main() body serializeAndDeserializeFunction(); serializeAndDeserializeClass(); } } |
Output:
Run original function: Hello 10 Serialized function to ./serialized-fn Deserialized function from ./serialized-fn Run deserialized function: Hello 11 Serialized class to ./serialized-class Deserialized class from ./serialized-class Hello Java