java - 使用 ObjectInputStream#readUnshared() 时出现意外的 OutOfMemoryError

标签 java out-of-memory deserialization objectinputstream

ObjectInputStream 读取大量对象时,我遇到了 OOM与 readUnshared . MAT指出其内部句柄表是罪魁祸首,OOM 堆栈跟踪也是如此(本文末尾)。从各方面来看,这都不应该发生。此外,OOM 是否发生似乎取决于对象之前是如何写入的。

根据 this write-up on the topic , readUnshared应该通过在读取期间不创建句柄表条目来解决问题(而不是 readObject )(该写入是我发现 writeUnsharedreadUnshared 的方式,我以前没有注意到)。

然而,从我自己的观察看来,readObjectreadUnshared行为相同,OOM 是否发生取决于对象是否用 reset() after each write 写入。 (是否使用 writeObjectwriteUnshared 无关紧要,正如我之前所想的——我第一次运行测试时只是累了)。那是:

              writeObject   writeObject+reset   writeUnshared   writeUnshared+reset
readObject       OOM               OK               OOM                 OK
readUnshared     OOM               OK               OOM                 OK

So whether or not readUnshared has any effect actually seems to be completely dependent on how the object was written. This is surprising and unexpected to me. I did spend some time tracing through the readUnshared code path but, and granted it was late and I was tired, it wasn't apparent to me why it would still be using handle space and why it would depend on how the object was written (however, I now have an initial suspect although I have yet to confirm, described below).

From all of my research on the topic so far, it appears writeObject with readUnshared should work.

Here is the program I've been testing with:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;


public class OOMTest {

    // This is the object we'll be reading and writing.
    static class TestObject implements Serializable {
        private static final long serialVersionUID = 1L;
    }

    static enum WriteMode {
        NORMAL,     // writeObject
        RESET,      // writeObject + reset each time
        UNSHARED,   // writeUnshared
        UNSHARED_RESET // writeUnshared + reset each time
    }

    // Write a bunch of objects.
    static void testWrite (WriteMode mode, String filename, int count) throws IOException {
        ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(filename)));
        out.reset();
        for (int n = 0; n < count; ++ n) {
            if (mode == WriteMode.NORMAL || mode == WriteMode.RESET)
                out.writeObject(new TestObject());
            if (mode == WriteMode.UNSHARED || mode == WriteMode.UNSHARED_RESET)
                out.writeUnshared(new TestObject());
            if (mode == WriteMode.RESET || mode == WriteMode.UNSHARED_RESET)
                out.reset();
            if (n % 1000 == 0)
                System.out.println(mode.toString() + ": " + n + " of " + count);
        }
        out.close();
    }

    static enum ReadMode {
        NORMAL,     // readObject
        UNSHARED    // readUnshared
    }

    // Read all the objects.
    @SuppressWarnings("unused")
    static void testRead (ReadMode mode, String filename) throws Exception {
        ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(filename)));
        int count = 0;
        while (true) {
            try {
                TestObject o;
                if (mode == ReadMode.NORMAL)
                    o = (TestObject)in.readObject();
                if (mode == ReadMode.UNSHARED)
                    o = (TestObject)in.readUnshared();
                //
                if ((++ count) % 1000 == 0)
                    System.out.println(mode + " (read): " + count);
            } catch (EOFException eof) {
                break;
            }
        }
        in.close();
    }

    // Do the test. Comment/uncomment as appropriate.
    public static void main (String[] args) throws Exception {
        /* Note: For writes to succeed, VM heap size must be increased.
        testWrite(WriteMode.NORMAL, "test-writeObject.dat", 30_000_000);
        testWrite(WriteMode.RESET, "test-writeObject-with-reset.dat", 30_000_000);
        testWrite(WriteMode.UNSHARED, "test-writeUnshared.dat", 30_000_000);
        testWrite(WriteMode.UNSHARED_RESET, "test-writeUnshared-with-reset.dat", 30_000_000);
        */
        /* Note: For read demonstration of OOM, use default heap size. */
        testRead(ReadMode.UNSHARED, "test-writeObject.dat"); // Edit this line for different tests.
    }

}

重新创建该程序问题的步骤:
  • 使用 testWrite 运行测试程序s 未注释(且 testRead 未调用),堆大小设置为高,因此 writeObject不会导致OOM。
  • 使用 testRead 第二次运行测试程序使用默认堆大小取消注释(和 testWrite 未调用)。

  • 需要明确的是:我不是在同一个 JVM 实例中进行写入和读取。我的写入发生在与我的读取不同的程序中。上面的测试程序乍一看可能有点误导,因为我将写入和读取测试都塞进了同一个源中。

    不幸的是,我所处的真实情况是我有一个包含许多用 writeObject 编写的对象的文件。 (没有 reset ),这将需要相当长的时间来重新生成(以天为单位)(而且 reset 使输出文件很大),所以如果可能的话,我想避免这种情况。另一方面,我目前无法使用 readObject 读取文件。 ,即使堆空间已达到我系统上的最大可用空间。

    值得注意的是,在我的真实情况下,我不需要对象流句柄表提供的缓存。

    所以我的问题是:
  • 到目前为止,我所有的研究都表明 readUnshared 之间没有联系。的行为以及对象的编写方式。这里发生了什么?
  • 鉴于数据是用 writeObject 写入的,有什么方法可以避免读取时的 OOM没有 reset ?

  • 我不完全确定为什么 readUnshared无法解决这里的问题。

    我希望这很清楚。我在这里空着跑,所以可能输入了奇怪的词。

    来自 comments在下面的答案中:

    If you're not calling writeObject() in the current instance of the JVM you should not be consuming memory by calling readUnshared().



    我所有的研究都表明相同,但令人困惑的是:
  • 这是 OOM 堆栈跟踪,指向 readUnshared :
    Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at java.io.ObjectInputStream$HandleTable.grow(ObjectInputStream.java:3464)
    at java.io.ObjectInputStream$HandleTable.assign(ObjectInputStream.java:3271)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1789)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1350)
    at java.io.ObjectInputStream.readUnshared(ObjectInputStream.java:460)
    at OOMTest.testRead(OOMTest.java:40)
    at OOMTest.main(OOMTest.java:54)
    
  • 这是一个 video of it happening (在最近的测试程序编辑之前录制的视频,视频相当于新测试程序中的ReadMode.UNSHAREDWriteMode.NORMAL)。
  • 这里是 some test data files ,其中包含 30,000,000 个对象(压缩后的大小只有 360 KB,但请注意它会扩展到惊人的 2.34 GB)。这里有四个测试文件,每个文件都是用writeObject的各种组合生成的。/writeUnsharedreset .读取行为仅取决于它的写入方式,与 readObject 无关。对比 readUnshared .请注意 writeObject对比 writeUnshared数据文件逐字节相同,我无法决定这是否令人惊讶。


  • 我一直盯着ObjectInputStream代码 from here .我目前的嫌疑人是 this line , 出现在 1.7 和 1.8 中:
    ObjectStreamClass desc = readClassDesc(false);
    

    哪里boolean参数为 true用于非共享和 false为正常。在所有其他情况下,“未共享”标志会传播到其他调用,但在这种情况下,它被硬编码为 false ,从而导致在读取序列化对象的类描述时将句柄添加到句柄表中,即使在 readUnshared用来。 AFAICT,这是唯一一次未将未共享标志传递给其他方法的情况,因此我关注它。

    这与例如相反。 this line未共享标志被传递到 readClassDesc . (如果有人想深入了解,您可以跟踪从 readUnshared 到这两行的调用路径。)

    但是,我还没有确认其中任何一个是重要的,也没有解释为什么false在那里硬编码。这只是我正在研究的当前轨道,它可能被证明毫无意义。

    另外,fwiw,ObjectInputStream确实有一个私有(private)方法,clear ,清除句柄表。我做了一个实验,每次阅读后我都称之为(通过反射),但它破坏了一切,所以这是不行的。

    最佳答案

    However, it seems that if the objects were written using writeObject() rather than writeUnshared(), then readUnshared() does not decrease handle table usage.



    那是正确的。 readUnshared()仅减少归因于 readObject() 的句柄表使用量.如果您在使用 writeObject() 的同一个 JVM 中而不是 writeUnshared() , 处理归因于 writeObject() 的表使用情况没有减少readUnshared() .

    关于java - 使用 ObjectInputStream#readUnshared() 时出现意外的 OutOfMemoryError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42733364/

    相关文章:

    c# - XmlSerializer 不显示对现有实例的更改

    excel - 将单元格从一张纸复制到另一张纸时出现内存不足错误

    c# - 什么导致asp.net内存不足异常

    Android应用程序运行内存大小限制

    delphi - 未加载自定义控件的已发布 TStrings 属性

    java - 用于随机和顺序访问的快速数据结构

    java - (Java) 如何导入和显示 Sprite ?

    java - java中的getsubimage()函数

    java - 使用remove方法之前/之后重新填充arrayList的效果

    java - java中的字符串到日期json解析