Including outside variables when serializing an object
Asked Answered
G

1

6

I'm trying to use Java 8 lambdas and have a general question about object serialization. For example the following input prints 5 if the executor.execute has only one method and runs the code block without serializing it. However if I serialize the lambda expression via SerializedLambda and deserialize it back, it prints null since it doesn't have the previous context in this new deserialized object. Moreover, it compiles without any complaint since the first context resolves outside variables. (finalVar in this example):

final int finalVar = 5;
executor.execute(() -> {
    System.out.println(finalVar);
});

I wonder whether it's possible to tell the SerializedLambda to include finalVar into serialization output without implementing an interface that has a field for finalVar variable and set the value of it to a field when constructing. AFAIK, this is the cleanest way to do such thing in Java:

final int finalVar = 5;
executor.execute(new Runnable() {
    int myVar = finalVar;

    public void run() { 
         System.out.println(myVar);
    }
);

I'm not even sure about that but I think the compiler can find out the outside variables and also serialize and include them when I try to serialize that lambda. Is there any trick for Java to do such thing or is there any language that has such feature?

Goldfilled answered 1/12, 2014 at 2:54 Comment(4)
Yes, serialized lambdas should automatically include captured variables without any special magic.Catechin
Perhaps it is related to the Eclipse bug described here: #23837715Seriema
What are your OS/IDE/Java versions? I can't reproduce this.Soiree
It actually works, the reason was one of the outside variables wasn't serializable so it couldn't serialize the lambda.Goldfilled
R
0

Regardless of variable scope, serialized lambdas will include outside variables as long as the types of those variables are Serializable. Make sure that's the case and you're good to go.

Reverential answered 8/3, 2015 at 19:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.