How to serialize a lambda?
Asked Answered
S

6

175

How can I elegantly serialize a lambda?

For example, the code below throws a NotSerializableException. How can I fix it without creating a SerializableRunnable "dummy" interface?

public static void main(String[] args) throws Exception {
    File file = Files.createTempFile("lambda", "ser").toFile();
    try (ObjectOutput oo = new ObjectOutputStream(new FileOutputStream(file))) {
        Runnable r = () -> System.out.println("Can I be serialized?");
        oo.writeObject(r);
    }

    try (ObjectInput oi = new ObjectInputStream(new FileInputStream(file))) {
        Runnable  r = (Runnable) oi.readObject();
        r.run();
    }
}
Selfdefense answered 2/4, 2014 at 10:2 Comment(1)
While this is possible (see the selected answer), everyone should probably think twice about actually doing this. It is officially "strongly discouraged" and can have serious security implications.Rory
S
299

Java 8 introduces the possibility to cast an object to an intersection of types by adding multiple bounds. In the case of serialization, it is therefore possible to write:

Runnable r = (Runnable & Serializable)() -> System.out.println("Serializable!");

And the lambda automagically becomes serializable.

Selfdefense answered 2/4, 2014 at 10:9 Comment(13)
Very interesting - this feature seems to be quite powerful. Is there any use of such a cast expression outside of casting lambdas? E.g. is it now also possible to do something similar with an ordinary anonymous class?Nephology
What I meant was: is there any way to instantiate an anonymous class implementing two interfaces similar to the instantiated lambda expression in your example. But I just looked into it and it seems there is no new syntax for doing something like that.Nephology
@Nephology The facility to cast to an intersection type was added in order to provide a target type for type inference of lambdas. Since AICs have a manifest type (i.e., its type is not inferred) casting an AIC to an intersection type isn't useful. (It is possible, just not useful.) To have an AIC implement multiple interfaces, you have to create a new subinterface that extends all of them, and then instantiate that.Condescend
Will this produce a compiler warning, saying no serialVersionUID is defined?Guardafui
@cypressious No compiler warning.Selfdefense
can SerializedLambda another alternative for serialization ?Houghton
Note: this only works if you apply the cast during construction. The following will throw a ClassCastException: Runnable r = () -> System.out.println("Serializable!"); Runnable serializableR = (Runnable & Serializable)r;Headset
@Headset Yes see also: #25392156Selfdefense
@Headset why shouldnt it? You are trying to cast Runnable to Serializable. No different outcome possibleUnderwood
@cypressious From the Serializable docs: If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification.Barbi
@StuartMarks "you have to create a new subinterface that extends all of them", that's why it is useful, much like mixin.Kelton
(Runnable & Serializable) () -> System.exit(0); byeYetac
If you use var instead of an explicit type, you can use the object both as Runnable and Serializable without having to cast, for example when calling a method expecting a Serializable argument. More on this here: blog.codefx.org/java/intersection-types-varWindup
N
30

Very ugly cast. I prefer to define a Serializable extension to the functional interface I'm using

For example:

interface SerializableFunction<T,R> extends Function<T,R>, Serializable {}
interface SerializableConsumer<T> extends Consumer<T>, Serializable {}

then the method accepting the lambda can be defined as such :

private void someFunction(SerializableFunction<String, Object> function) {
   ...
}

and calling the function you can pass your lambda without any ugly cast:

someFunction(arg -> doXYZ(arg));
Nodus answered 15/8, 2017 at 18:27 Comment(1)
I like this answer because then any external caller you don't write will automatically also be serializable. If you want objects submitted to be serializable, your interface should be serializable, which is kind of the point of an interface. However, the question did say "without creating a SerializableRunnable 'dummy' interface"Delagarza
L
25

The same construction can be used for method references. For example this code:

import java.io.Serializable;

public class Test {
    static Object bar(String s) {
        return "make serializable";
    }

    void m () {
        SAM s1 = (SAM & Serializable) Test::bar;
        SAM s2 = (SAM & Serializable) t -> "make serializable";
    }

    interface SAM {
        Object action(String s);
    }
}

defines a lambda expression and a method reference with a serializable target type.

Lindquist answered 25/5, 2014 at 1:1 Comment(0)
L
8

In case someone falls here while creating Beam/Dataflow code :

Beam has his own SerializableFunction Interface so no need for dummy interface or verbose casts.

Leontineleontyne answered 19/7, 2019 at 8:13 Comment(0)
G
4

If you are willing to switch to another serialization framework like Kryo, you can get rid of the multiple bounds or the requirement that the implemented interface must implement Serializable. The approach is to

  1. Modify the InnerClassLambdaMetafactory to always generate the code required for serialization
  2. Directly call the LambdaMetaFactory during deserialization

For details and code see this blog post

Geophyte answered 7/5, 2017 at 11:59 Comment(1)
The post was moved here: ruediste.github.io/java/kryo/2017/05/07/…Ansermet
H
0

To add to other answers, you can create a serializable lambda by using the cast expression or by using a new interface that extends Serializable as shown in other answers. Notice that the resulting objects don't necessarily play nice with default methods of the functional interfaces (for example). The third solution, far from ideal because it does not ensure that the right hand side operand is serializable, does generate a serializable object.

@Test
public void testCasetExpression() {
    Predicate<Integer> p1 = (Predicate<Integer> & Serializable)i -> true;
    Predicate<Integer> p2 = (Predicate<Integer> & Serializable)i -> true;
    
    Predicate<Integer> p3 = p1.and(p2);
    Assertions.assertFalse(p3 instanceof Serializable); // Notice false
}

interface SerializablePredicateV1<T> extends Predicate<T>, Serializable {}

@Test
public void testInterfaceV1() {
    Predicate<Integer> p1 = (SerializablePredicateV1)i -> true;
    Predicate<Integer> p2 = (SerializablePredicateV1)i -> true;
    
    Predicate<Integer> p3 = p1.and(p2);
    Assertions.assertFalse(p3 instanceof Serializable); // Notice false
}

interface SerializablePredicateV2<T> extends Predicate<T>, Serializable {
    
    @Override
    default SerializablePredicateV2<T> and(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }

}

@Test
public void testInterfaceV2() {
    Predicate<Integer> p1 = (SerializablePredicateV2)i -> true;
    Predicate<Integer> p2 = (SerializablePredicateV2)i -> true;
    
    Predicate<Integer> p3 = p1.and(p2);
    Assertions.assertTrue(p3 instanceof Serializable); // Notice true
    
    Predicate<Integer> p4 = i -> true; // Not serializable
    
    Predicate<Integer> p5 = p1.and(p4);
    // true but will fail because p4 is not serializable
    Assertions.assertTrue(p5 instanceof Serializable);  
}

// Not a Predicate anymore :(
interface SerializablePredicateV3<T> extends Serializable {

    boolean test(T t);

    default SerializablePredicateV3<T> and(SerializablePredicateV3<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }
}

@Test
public void testInterfaceV3() {
    SerializablePredicateV3<Integer> p1 = (SerializablePredicateV3)i -> true;
    SerializablePredicateV3<Integer> p2 = (SerializablePredicateV3)i -> true;
    
    SerializablePredicateV3<Integer> p3 = p1.and(p2);
}
Hageman answered 12/10, 2023 at 22:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.