unclosed流导致java中的内存泄漏? [英] Do unclosed streams cause memory leaks in java?

查看:266
本文介绍了unclosed流导致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.

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

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