当前位置: 动力学知识库 > 问答 > 编程问答 >

java - KML marshal produces zero-length files

问题描述:

In Java code, I spawn a Thread which every second gathers DIS packets from a simulator, and tries to format KML output. In my Java code I am creating a Document, with Styles and Placemarks and Polygons. Once every second I can see that the "marshal" API routine does indeed create a KML file with my data. However, randomly sometimes it creates a complete file, and sometimes it creates a zero-length file. Even when I turn my DIS packet generator off, and leave my Java code still running, it continues to randomly create a complete file, and sometimes create a zero-length file. When I change my timer from every second to every 10 seconds, the behavior occurs every 10 seconds.

I tried using marshal() to a File object, and to an OutputStream object; Same weird behavior.

网友答案:

It could be due to concurrent access. Creating a marshaller is an expensive operation, it takes time and as far as I know marshallers are not threadsafe. I use the jaxb connector in Restlet, coupled with JAK, and that's a good example on how to create marshallers and cache them in a threadsafe way:

/** Use thread identity to preserve safety of access to marshalers. */
private final ThreadLocal<javax.xml.bind.Marshaller> marshaller = new ThreadLocal<javax.xml.bind.Marshaller>() {

See there how the marshaller is created in a synchronized method and then stored in a ThreadLocal variable.

分享给朋友:
您可能感兴趣的文章:
随机阅读: