Serialization opt-in syntax (again)

Brian Goetz brian.goetz at
Sat Sep 29 14:14:13 PDT 2012

> Anyway, I'm am still not convinced that making a lambda Serializable add a cost that worth the pain of creating a new syntax.

Here's the reason this is important: libraries.  We have lots of combinators that take a lambda and produce a new lambda, like Comparators.compose.  

We'd like to write it like (modulo generics):

Comparator<T> compose(Comparator<T> one, Comparator<T> two) {
    return (x, y) -> { 
       int cmp =, y);
       return cmp != 0 ? cmp :, y);

But instead, we write it like this:

    private static class ComposedComparator<T>
        implements Comparator<T>, Serializable {

        private static final long serialVersionUID = -3088981872625314196L;

        private final Comparator<? super T> first;
        private final Comparator<? super T> second;

        private ComposedComparator(Comparator<? super T> first, Comparator<? super T> second) {
            this.first = Objects.requireNonNull(first);
            this.second = Objects.requireNonNull(second);

        public int compare(T c1, T c2) {
            int res =, c2);
            return (res != 0) ? res :, c2);

    public static<T> Comparator<T> compose(Comparator<? super T> first, Comparator<? super T> second) {
        return new ComposedComparator<>(first, second);

We do it this way entirely for serialization; if the user has two serializable comparators and wants to compose them, there should be a way of making the result serializable.  Doubling the surface area of the library is not a good option.  Nor is making it so that the result cannot be serialziable.  And if the library has to choose between lambda and serialization support, that's not so good either.  

You should be able to write these combinators with lambda without giving up on serializability.  That's why we need this.  

> Brian, do you have data about the supplementary cost of creating Serializable lambda ?

Sadly I do not  yet, and may not for a while.  But I know that there will be a nonzero footprint and capture cost, and it imposes some additional hurdles on some VM optimizations we want to do.  I think that's all the information we will ahve for a while, but I think we have to go on the assumption that the cost will be enough that "make all lambdas serializable" is not a very good choice.  

More information about the lambda-spec-experts mailing list