我正在使用 JAXB 将 java 对象编码和解码到 xml,反之亦然。 我正在编码(marshal)的对象具有字节数组属性。如果字节数组很大,我就会遇到 OOM。
这是我正在做的编码:
StringWriter writer = new StringWriter();
jaxbContext = JAXBContext.newInstance("package name");
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE);
jaxbMarshaller.marshal(myObject, writer);
return writer.toString();
我在线遇到的错误:
jaxbMarshaller.marshal(myObject, writer);
这是堆栈跟踪:
java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Unknown Source)
at java.lang.AbstractStringBuilder.expandCapacity(Unknown Source)
at java.lang.AbstractStringBuilder.ensureCapacityInternal(Unknown Source)
at java.lang.AbstractStringBuilder.append(Unknown Source)
at java.lang.StringBuffer.append(Unknown Source)
at java.io.StringWriter.write(Unknown Source)
at java.io.BufferedWriter.flushBuffer(Unknown Source)
at java.io.BufferedWriter.flush(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.cleanUp(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.write(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.marshal(Unknown Source)
at javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(Unknown Source)
这里是java内存统计信息:
uintx AdaptivePermSizeWeight = 20 {product}
intx CompilerThreadStackSize = 0 {pd product}
uintx ErgoHeapSizeLimit = 0 {product}
uintx HeapSizePerGCThread = 87241520 {product}
uintx InitialHeapSize := 90006400 {product}
uintx LargePageHeapSizeThreshold = 134217728 {product}
uintx MaxHeapSize := 1440743424 {product}
uintx MaxPermSize = 85983232 {pd product}
uintx PermSize = 21757952 {pd product}
intx ThreadStackSize = 0 {pd product}
intx VMThreadStackSize = 0 {pd product}
非常感谢任何帮助。
最佳答案
或者,您可以在编码 JAXB 时使用流模式。详情请引用以下帖子:
How to stream large Files using JAXB Marshaller?
此方法将阻止您的应用在 StringWriter 对象中加载大量数据,从而导致此 OutOfMemoryError
关于java - 使用 JAXB 编码(marshal)时出现内存不足错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33073933/