简体   繁体   English

当此方法引发异常时,会导致内存泄漏吗?

[英]Will this method cause a memory leak when it throws an exception?

Will this method cause a memory leak when it throws an exception? 当此方法引发异常时,会导致内存泄漏吗?

public static void warnUser(String name) {
    try {
        BufferedWriter writer = new BufferedWriter(new FileWriter(dir + "warnings.txt", true));
        writer.newLine();
        writer.write(name);
        writer.close();
    } catch (Exception e) {
        System.out.println(e.getMessage());
        System.err.println("error giving warning to: " + name);
    }
}

Is this better? 这是否更好?

    public static void warnUser(String name) {
    try (BufferedWriter writer = new BufferedWriter(new FileWriter(dir + "warnings.txt", true))) {
        writer.newLine();
        writer.write(name);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        System.err.println("error giving warning to: " + name);
    }
}

A memory leak? 内存泄漏? No, once execution leaves this method, be it through return or throwing an exception, the BufferedWriter object will no longer be reachable, and becomes eligible for garbage collection. 不,一旦执行离开此方法,无论是通过返回还是引发异常,则BufferedWriter对象将不再可访问,并且可以进行垃圾回收。

However, as you are not invoking the close method when an exception is thrown while writing to the file, the file will remain open, preventing anybody from using it, and possibly exhausting the limited number of files that the operating system can keep open at any given time, until finally the garbage collector gets around to collecting the object, which will trigger its finalizer which closes the file, but you don't know when that is (it can easily take hours if you're unlucky). 但是,由于在写入文件时引发异常时您没有调用close方法,因此文件将保持打开状态,从而阻止任何人使用它,并可能耗尽操作系统可以随时打开的有限数量的文件。给定时间,直到垃圾回收器最终收集该对象,这将触发其终结器来关闭文件,但您不知道何时结束(如果不幸的话,可能很容易花费数小时)。 This is why operating system resources such as files should be closed right when your program no longer needs them. 这就是为什么在程序不再需要诸如文件之类的操作系统资源时就应该将其关闭的原因。 That's why InputStreams have a close method, and Java has a try-with-resources statement. 这就是为什么InputStreams具有close方法,而Java具有try-with-resources语句的原因。

You should assume it does. 您应该假设确实如此。

Close the writer in a finally block. 在finally块中关闭编写器。

I think it's best to always be in the habit of using the finally block to close like so: 我认为最好总是养成这样使用finally块关闭的习惯:

public static void warnUser(String name) {
    BufferedWriter writer = null;

    try {
        writer = new BufferedWriter(new FileWriter(dir + "warnings.txt", true));
        writer.newLine();
        writer.write(name);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        System.err.println("error giving warning to: " + name);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
            }
        }
    }
}

Nope , it will not cause a memory leak. 不会,它不会导致内存泄漏。 The writer object will marked for garbage collection implicitly once the scope of the method ends. 一旦方法的作用域结束,writer对象将隐式标记为垃圾回收。 But it is a good practice to close the writer object so that the file in question gets closed too. 但是,关闭writer对象是一种很好的做法,这样也可以关闭有问题的文件。

In cases where exception is thrown check in the finally block if the writer object is null or not. 在引发异常的情况下,检查一下writer块是否为null。 If it has been instantiated then close it . 如果已实例化,则将其关闭。 That is what we do in cases where a SQLException is thrown by the code using Jdbc so that the resources being used are released. 在使用Jdbc的代码抛出SQLException从而释放所使用的资源的情况下,我们就是这样做的。

finally
{ 
  if (writer!= null) 
  { 
    try {
            writer.close();
        } 
    catch (IOException exception2) 
        {
          // Do Nothing
        }
  }
}

.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM