Serializing a priority queue in scala

╄→尐↘猪︶ㄣ 提交于 2019-12-02 11:01:07

问题


I am trying to serialize a mutable PriorityQueue in scala (2.10) and am getting a NotSerializableException when writing the object to an ObjectOutputStream. I made a simple test case:

import java.io.{ByteArrayOutputStream, ObjectOutputStream}
import scala.collection.mutable

object Test extends App {
  val pq = new mutable.PriorityQueue[Int]()
  val oos = new ObjectOutputStream(new ByteArrayOutputStream())
  oos.writeObject(pq)
}

The exception is

Exception in thread "main" java.io.NotSerializableException:scala.collection.mutable.PriorityQueue$ResizableArrayAccess
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1180)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1528)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1493)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1416)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:346)
at Test$.main(Test.scala:7)

It seems like a PriorityQueue should be serializable, is there something I can do to get around this?


回答1:


This should be reported as a bug - the fix is to simply make the nested ResizableArrayAccess class inherit Serializable.

Technically, maybe you could use reflection to remove the private and final modifiers on the resarr field in the priority queue class, then set it to null before serialization.

Otherwise, converting the priority queue to a, say, array before serialization and vice versa on deserialization would avoid this exception. You could roll in your own wrapper around the PriorityQueue to implement custom serialization/deserialization.

Note: This issue has been resolved in Scala 2.11.0-M7 (SI-7568)



来源:https://stackoverflow.com/questions/15790757/serializing-a-priority-queue-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!