To test the Serialization exception in spark I wrote a task in 2 ways.
First way:
package examples
import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
object dd {
def main(args: Array[String]):Unit = {
val sparkConf = new SparkConf
val sc = new SparkContext(sparkConf)
val data = List(1,2,3,4,5)
val rdd = sc.makeRDD(data)
val result = rdd.map(elem => {
funcs.func_1(elem)
})
println(result.count())
}
}
object funcs{
def func_1(i:Int): Int = {
i + 1
}
}
This way spark works pretty good.
While when I change it to following way, it does not work and throws NotSerializableException.
Second way:
package examples
import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
object dd {
def main(args: Array[String]):Unit = {
val sparkConf = new SparkConf
val sc = new SparkContext(sparkConf)
val data = List(1,2,3,4,5)
val rdd = sc.makeRDD(data)
val handler = funcs
val result = rdd.map(elem => {
handler.func_1(elem)
})
println(result.count())
}
}
object funcs{
def func_1(i:Int): Int = {
i + 1
}
}
I know the reason I got error "task is not serializable" is because I am trying to send an unserializable object funcs
from driver node to worker node in second example. For second example, if I make object funcs
extend Serializable
, this error will gone.
But In my view, because funcs
is an object rather than a class, it is a singleton and supposed to be serialized and shipped from driver to workers instead of instantiating within a worker node itself. In this scenario, although way to use object funcs
is different, I guess the unserializable object funcs
is shipped from driver node to worker node in both of these 2 examples.
My question is why the first example can be run successfully but second one fails with 'task unserializable' exception.