有没有办法预测和防止 OOM 异常?
Is there a way to anticipate and prevent an OOM exception?
我从 HttpUrlConnection
对象获取输入流。 http响应是一个JSON格式的网页,大小大于50Mb。
通过将此输入流转化为字符串变量,我的应用程序最终因致命异常而崩溃 OutOfMemoryError: Failed to allocate a 51096576 byte allocation with 25165824 free bytes and 47MB until OOM, max allowed footprint 244303608, growth limit 268435456
。
应用程序似乎无法为该字符串分配所需的内存。
有没有办法预测 OOM
异常? (例如,当输入流几乎耗尽所有堆时。至少,当这种情况即将发生时,我可以改变我的应用程序的行为)
Is there a way to anticipate an OOM exception ?
不,抱歉。
say for example, when the inputStream will almost eat up all of the heap
这不是 OutOfMemoryException
的原因。当您尝试分配内存块并且没有足够大的空闲内存块来满足您的请求时,您会得到一个 OutOfMemoryException
。
在您的情况下,您有足够的空闲堆 space。您要求分配一个巨大的块。
By getting this input stream into a string variable
这就是你困难的根源。使用流式 JSON 解析器(Jackson 和 Gson 都有流式模式 IIRC)并使用 JSON 小块。
我从 HttpUrlConnection
对象获取输入流。 http响应是一个JSON格式的网页,大小大于50Mb。
通过将此输入流转化为字符串变量,我的应用程序最终因致命异常而崩溃 OutOfMemoryError: Failed to allocate a 51096576 byte allocation with 25165824 free bytes and 47MB until OOM, max allowed footprint 244303608, growth limit 268435456
。
应用程序似乎无法为该字符串分配所需的内存。
有没有办法预测 OOM
异常? (例如,当输入流几乎耗尽所有堆时。至少,当这种情况即将发生时,我可以改变我的应用程序的行为)
Is there a way to anticipate an OOM exception ?
不,抱歉。
say for example, when the inputStream will almost eat up all of the heap
这不是 OutOfMemoryException
的原因。当您尝试分配内存块并且没有足够大的空闲内存块来满足您的请求时,您会得到一个 OutOfMemoryException
。
在您的情况下,您有足够的空闲堆 space。您要求分配一个巨大的块。
By getting this input stream into a string variable
这就是你困难的根源。使用流式 JSON 解析器(Jackson 和 Gson 都有流式模式 IIRC)并使用 JSON 小块。