[infinispan-dev] Lambda Serialization

William Burns mudokonman at gmail.com
Tue Feb 9 11:36:27 EST 2016


I wanted to propose a pretty simple way of making the lambdas serializable
by default that I stumbled upon while working on another issue.

I noticed that in the method resolution of the compiler it does some nice
things [1].  To be more specific when you have 2 methods with the same name
but vary by argument types, it will attempt to pick the most "specific"
one.  Specific in this case you can think of if I can cast one argument
type to the other but it can't be cast to this type, then this one is most
specific.

Here is an example, given the following class

interface SerializableFunction<T, R> extends Serializable, Function<T, R>

The stream interface already defines:

   Stream map(Function<? super T, ? extends R> mapper);

But we could add this to the CacheStream interface

  CacheStream map(SerializableFunction<? super T, ? extends R> mapper);

In this case you have 2 different map methods accessible from your
CacheStream instance.  When passing a lambda the Java compiler will
automatically choose the most specific one (in this case the
SerializableFunction one since Function can't be cast to
SerializableFunction).  This will then make the lambda automatically
Serializable.  In this way nothing special has to be done (ie. explicit
cast) to make the instance Serializable.

This allows anyone using our Cache interface to immediately get lambdas
that are Serializable when using Streams.

The main problem however would be ambiguity because the Serialization would
only be applied assuming you are using a defined class of CacheStream etc.
Also this means there are 2 methods (but that seems fine to me), so it
could cause a bit of confusion.  The non serialization method is still
helpful if people want to their own Externalizer, since their
implementation doesn't have to implement Serializable then.

What do you guys think?  It seems like a decent compromise to me.

 - Will





[1]
https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.12.2.5
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.jboss.org/pipermail/infinispan-dev/attachments/20160209/3130d5d6/attachment.html 


More information about the infinispan-dev mailing list