java - 出现内存不足异常的根本原因是什么?我们怎样才能克服这个问题呢?

标签 java garbage-collection inputstream heap-memory outputstream

这是我通过输出流读取和写入的示例片段,我遇到了内存不足异常。

 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;
}
  1. What are the possible scenarios with the above snippet to get "out of memory exception" ?
  2. 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?
  3. How could I avoid Out of memory exception in general?

请澄清一下。

最佳答案

  1. 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 代码会报告此明显的异常

  1. 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?

由于您在方法中使用原始 InputStreamOutputStream,我们不知道哪种类型的实际 Stream 将传递给此方法,因此显式关闭这些 Stream 是个好主意。

  1. How could I avoid Out of memory exception in general?

这个问题已经作为您第一个问题的回答。

请参阅有关处理 IO 操作的大文件的 SE 问题:

Java OutOfMemoryError in reading a large text file

关于java - 出现内存不足异常的根本原因是什么?我们怎样才能克服这个问题呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37163250/

相关文章:

java - 如何在安卓上创建pdf文件

java - WebDriver 自动化验证电子邮件

java Gradle 仅将某些库复制到文件夹

node.js - Nodejs/V8 如何知道原生对象有多大?

java - java中InputStream中的read函数如何读取一个字节并将其作为int返回?

java - 如何在不使用 Joda Time 的情况下计算特定工作时间的两个日期之间的小时数?

c# - 通过 lambda 使对象保持事件状态

java - 为什么大多数 JVM gc 不使用引用计数?

java - 为什么 InputStreamReader 在从 jar 读取时抛出 NPE?

java - 从 java HTTP 响应获取正确的类型/编码