|
| 1 | +package com.twitter.chill |
| 2 | + |
| 3 | +import _root_.java.lang.{ Iterable => JIterable } |
| 4 | + |
| 5 | +/** |
| 6 | + * A Kryo serializer for serializing results returned by asJavaIterable. |
| 7 | + * |
| 8 | + * The underlying object is scala.collection.convert.Wrappers$IterableWrapper. |
| 9 | + * Kryo deserializes this into an AbstractCollection, which unfortunately doesn't work. |
| 10 | + * |
| 11 | + * Ported from Apache Spark's KryoSerializer.scala. |
| 12 | + */ |
| 13 | +private class JavaIterableWrapperSerializer extends KSerializer[JIterable[_]] { |
| 14 | + |
| 15 | + import JavaIterableWrapperSerializer._ |
| 16 | + |
| 17 | + override def write(kryo: Kryo, out: Output, obj: JIterable[_]): Unit = { |
| 18 | + // If the object is the wrapper, simply serialize the underlying Scala Iterable object. |
| 19 | + // Otherwise, serialize the object itself. |
| 20 | + if (obj.getClass == wrapperClass && underlyingMethodOpt.isDefined) { |
| 21 | + kryo.writeClassAndObject(out, underlyingMethodOpt.get.invoke(obj)) |
| 22 | + } else { |
| 23 | + kryo.writeClassAndObject(out, obj) |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + override def read(kryo: Kryo, in: Input, clz: Class[JIterable[_]]): JIterable[_] = { |
| 28 | + kryo.readClassAndObject(in) match { |
| 29 | + case scalaIterable: Iterable[_] => |
| 30 | + scala.collection.JavaConversions.asJavaIterable(scalaIterable) |
| 31 | + case javaIterable: JIterable[_] => |
| 32 | + javaIterable |
| 33 | + } |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +private object JavaIterableWrapperSerializer { |
| 38 | + // The class returned by asJavaIterable (scala.collection.convert.Wrappers$IterableWrapper). |
| 39 | + val wrapperClass = scala.collection.JavaConversions.asJavaIterable(Seq(1)).getClass |
| 40 | + |
| 41 | + // Get the underlying method so we can use it to get the Scala collection for serialization. |
| 42 | + private val underlyingMethodOpt = { |
| 43 | + try Some(wrapperClass.getDeclaredMethod("underlying")) catch { |
| 44 | + case e: Exception => |
| 45 | + None |
| 46 | + } |
| 47 | + } |
| 48 | +} |
0 commit comments