java.lang.ClassCastException 在远程服务器上的 spark 作业中使用 lambda 表达式

2022-09-01 11:32:45

我正在尝试使用 sparkjava.com 框架为我的apache spark作业构建一个Web api。我的代码是:

@Override
public void init() {
    get("/hello",
            (req, res) -> {
                String sourcePath = "hdfs://spark:54310/input/*";

                SparkConf conf = new SparkConf().setAppName("LineCount");
                conf.setJars(new String[] { "/home/sam/resin-4.0.42/webapps/test.war" });
                File configFile = new File("config.properties");

                String sparkURI = "spark://hamrah:7077";

                conf.setMaster(sparkURI);
                conf.set("spark.driver.allowMultipleContexts", "true");
                JavaSparkContext sc = new JavaSparkContext(conf);

                @SuppressWarnings("resource")
                JavaRDD<String> log = sc.textFile(sourcePath);

                JavaRDD<String> lines = log.filter(x -> {
                    return true;
                });

                return lines.count();
            });
}

如果我删除 lambda 表达式或将其放在一个简单的 jar 中,而不是 Web 服务(以某种方式是 servlet),它将运行而不会出现任何错误。但是在 servlet 中使用 lambda 表达式将导致以下异常:

15/01/28 10:36:33 WARN TaskSetManager: Lost task 0.0 in stage 0.0 (TID 0, hamrah): java.lang.ClassCastException: cannot assign instance of java.lang.invoke.SerializedLambda to field org.apache.spark.api.java.JavaRDD$$anonfun$filter$1.f$1 of type org.apache.spark.api.java.function.Function in instance of org.apache.spark.api.java.JavaRDD$$anonfun$filter$1
at java.io.ObjectStreamClass$FieldReflector.setObjFieldValues(ObjectStreamClass.java:2089)
at java.io.ObjectStreamClass.setObjFieldValues(ObjectStreamClass.java:1261)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1999)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1918)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1801)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1993)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1918)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1801)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1993)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1918)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1801)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1351)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371)
at org.apache.spark.serializer.JavaDeserializationStream.readObject(JavaSerializer.scala:62)
at org.apache.spark.serializer.JavaSerializerInstance.deserialize(JavaSerializer.scala:87)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:57)
at org.apache.spark.scheduler.Task.run(Task.scala:56)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:196)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

P.S:我尝试将球衣和javaspark与码头,雄猫和树脂相结合,所有这些都使我得出了相同的结果。


答案 1

你在这里看到的是一个后续错误,它掩盖了原始错误。

当 lambda 实例被序列化时,它们用于将其 JRE 特定实现从持久形式(即序列化Lambda 实例)中解体。还原实例后,将调用其方法以重新构建相应的 lambda 实例。正如文档所说,它将通过调用定义原始lambda的类的特殊方法来做到这一点(另请参阅此答案)。重要的一点是需要原始类,这就是你的情况所缺少的。writeReplaceSerializedLambdareadResolve

但是有一个...特殊。。。的行为。当它遇到异常时,它不会立即救助。它将记录异常并继续该过程,将当前正在读取的所有对象标记为错误,从而根据错误对象也将错误。只有在该过程结束时,它才会引发它遇到的原始异常。使它如此奇怪的是,它还将继续尝试设置这些对象的字段。但是当你看一下方法行 1806 时:ObjectInputStreamObjectInputStream.readOrdinaryObject

…
    if (obj != null &&
        handles.lookupException(passHandle) == null &&
        desc.hasReadResolveMethod())
    {
        Object rep = desc.invokeReadResolve(obj);
        if (unshared && rep.getClass().isArray()) {
            rep = cloneArray(rep);
        }
        if (rep != obj) {
            handles.setObject(passHandle, obj = rep);
        }
    }

    return obj;
}

您会看到,当报告非异常时,它不会调用该方法。但是,当替换没有发生时,继续尝试设置引荐来源网址的字段值不是一个好主意,但这正是这里发生的事情,因此会产生.readResolvelookupExceptionnullClassCastException

您可以轻松重现问题:

public class Holder implements Serializable {
    Runnable r;
}
public class Defining {
    public static Holder get() {
        final Holder holder = new Holder();
        holder.r=(Runnable&Serializable)()->{};
        return holder;
    }
}
public class Writing {
    static final File f=new File(System.getProperty("java.io.tmpdir"), "x.ser");
    public static void main(String... arg) throws IOException {
        try(FileOutputStream os=new FileOutputStream(f);
            ObjectOutputStream   oos=new ObjectOutputStream(os)) {
            oos.writeObject(Defining.get());
        }
        System.out.println("written to "+f);
    }
}
public class Reading {
    static final File f=new File(System.getProperty("java.io.tmpdir"), "x.ser");
    public static void main(String... arg) throws IOException, ClassNotFoundException {
        try(FileInputStream is=new FileInputStream(f);
            ObjectInputStream ois=new ObjectInputStream(is)) {
            Holder h=(Holder)ois.readObject();
            System.out.println(h.r);
            h.r.run();
        }
        System.out.println("read from "+f);
    }
}

编译这四个类并运行 。然后删除类文件并运行 。然后你会得到一个WritingDefining.classReading

Exception in thread "main" java.lang.ClassCastException: cannot assign instance of java.lang.invoke.SerializedLambda to field test.Holder.r of type java.lang.Runnable in instance of test.Holder
    at java.io.ObjectStreamClass$FieldReflector.setObjFieldValues(ObjectStreamClass.java:2089)
    at java.io.ObjectStreamClass.setObjFieldValues(ObjectStreamClass.java:1261)

(使用 1.8.0_20 进行测试)


底线是,一旦了解了发生了什么,您可能会忘记此序列化问题,解决您的问题所要做的就是确保定义lambda表达式的类在lambda被反序列化的运行时中也可用。

直接从 IDE 运行的 Spark Job 示例(默认情况下,spark-submit 分发 jar):

SparkConf sconf = new SparkConf()
  .set("spark.eventLog.dir", "hdfs://nn:8020/user/spark/applicationHistory")
  .set("spark.eventLog.enabled", "true")
  .setJars(new String[]{"/path/to/jar/with/your/class.jar"})
  .setMaster("spark://spark.standalone.uri:7077");

答案 2

我遇到了同样的错误,我用内部类替换了lambda,然后它工作了。我真的不明白为什么,并且重现这个错误是非常困难的(我们有一个服务器表现出这种行为,而不是其他地方)。

不起作用

this.variable = () -> { ..... }

收益 率java.lang.ClassCastException: cannot assign instance of java.lang.invoke.SerializedLambda to field MyObject.val$variable

工程

this.variable = new MyInterface() {
    public void myMethod() {
       .....
    }
};

推荐