简体   繁体   中英

Serializing a priority queue in scala

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?

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM