未关闭的流是否会导致 Java 中的内存泄漏? [英] Do unclosed streams cause memory leaks in java?

查看:76
本文介绍了未关闭的流是否会导致 Java 中的内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信开放流会导致 java 中的内存泄漏(至少 java 1.6 及更早版本确实存在此问题).

I believe open streams cause memory leak in java (at least java 1.6 and earlier did had this problem).

但是,在搜索时(甚至在这里),我发现有些人同意这一点,而其他人则不同意.所以,如果我写这个程序:

But, while searching (even here), I found some people agreeing with this while others do not. So, if I write this program:

import java.io.*;
public class CreatingMemoryLeak {

    public static void main(String args[])
    {
        String s = "xxxxxxx";
        InputStream in = new ByteArrayInputStream(ss.getBytes());
        BufferedInputStream bf = new BufferedInputStream(in);

        try {
            while(bf.read()>0)
            {
                System.out.println("got it");
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("Here is a input stream " + s +" causing a memory leak");

    }
}

如果我没有明确关闭 bf 流,它会导致内存泄漏吗?

and if I do not close the bf stream explicitly, will it cause a memory leak?

推荐答案

在 Java 中准确使用术语内存泄漏"很重要.

It's important to be precise in the use of the term 'memory leak' with respect to Java.

在 Java 中,内存泄漏发生在您的代码永久持有引用时,因此某些对象永远不会被垃圾回收.

In Java, a memory leak happens when your code holds a reference permanently, so that some object is never garbage collected.

未能关闭流在这个意义上不是内存泄漏.具有本机资源的流具有终结器;GC 最终将关闭它们.除非您持有对未关闭流的引用,否则它不是泄漏.

Failing to close a stream is not a memory leak in this sense. Streams that have native resources have finalizers; the GC will eventually close them down. Unless you hold a reference to the unclosed stream it isn't a leak.

然而,除了内存泄漏,还有其他类型的泄漏.大多数操作系统限制打开文件的数量.如果你没有关闭你的流,GC 可能需要很长时间来为你关闭它们;最终结果可能是您用完了系统文件描述符并且您的代码无法再打开一个文件.有些人会称之为泄漏,但称其为内存泄漏并不准确.

However, there are other kinds of leaks besides memory leaks. Most operating systems limit the number of open files. If you fail to close your streams, the GC may take a very long time to close them for you; the net result may be that you run out of system file descriptors and your code fails to open one more file. Some people will call this a leak, but it's not accuracy to call it a memory leak.

这篇关于未关闭的流是否会导致 Java 中的内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆