这是我通过输出流读取和写入的示例片段,我遇到了内存不足异常。
public static void readFileContent(InputStream in, OutputStream out) throws IOException {
byte[] buf = new byte[500000];
int nread;
int navailable;
int total = 0;
synchronized (in) {
try {
while((nread = in.read(buf, 0, buf.length)) >= 0) {
out.write(buf, 0, nread);
total += nread;
}
}
finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
out.flush();
buf = null;
}
- What are the possible scenarios with the above snippet to get "out of memory exception" ?
- Is it necessary to close the output stream here? And does stream, flush is enough or do we need to close the stream always? If so why?
- How could I avoid Out of memory exception in general?
请澄清一下。
最佳答案
- What are the possible scenarios with the above snippet to get "out of memory exception" ?
内存不足异常的根本原因有多种。引用oracle文档page了解更多详情。
java.lang.OutOfMemoryError:Java堆空间
:
原因:详细消息Java堆空间指示无法在Java堆中分配对象。
java.lang.OutOfMemoryError:超出 GC 开销限制
:
原因:详细信息“GC Overhead Limit Excessed”表示垃圾收集器一直在运行,Java 程序进展非常缓慢
java.lang.OutOfMemoryError:请求的数组大小超出 VM 限制
:
原因:详细消息“请求的数组大小超出 VM 限制”表示应用程序(或该应用程序使用的 API)尝试分配大于堆大小的数组。
java.lang.OutOfMemoryError:元空间
:
原因: Java 类元数据(Java 类的虚拟机内部表示)分配在 native 内存(此处称为元空间)中
java.lang.OutOfMemoryError:出于原因请求大小字节。交换空间不足?
:
原因:详细消息“出于原因请求大小字节。交换空间不足?”似乎是 OutOfMemoryError 异常。但是,当 native 堆的分配失败并且 native 堆可能接近耗尽时,Java HotSpot VM 代码会报告此明显的异常
- Is it necessary to close the output stream here? And does stream, flush is enough or do we need to close the stream always? If so why?
由于您在方法中使用原始 InputStream
和 OutputStream
,我们不知道哪种类型的实际 Stream 将传递给此方法,因此显式关闭这些 Stream 是个好主意。
- How could I avoid Out of memory exception in general?
这个问题已经作为您第一个问题的回答。
请参阅有关处理 IO 操作的大文件的 SE 问题:
关于java - 出现内存不足异常的根本原因是什么?我们怎样才能克服这个问题呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37163250/