6

当我在此方法中的块return内的两个值中都出现资源泄漏警告时,我在 Eclipse 中正常工作:try

@Override
public boolean isValid(File file) throws IOException
{
    BufferedReader reader = null;
    try
    {
        reader = new BufferedReader(new FileReader(file));
        String line;
        while((line = reader.readLine()) != null)
        {
            line = line.trim();
            if(line.isEmpty())
                continue;
            if(line.startsWith("#") == false)
                return false;
            if(line.startsWith("#MLProperties"))
                return true;
        }
    }
    finally
    {
        try{reader.close();}catch(Exception e){}
    }
    return false;
}

我不明白它是如何导致资源泄漏的,因为我reader在范围之外声明变量,在块try内添加资源并在块中使用另一个来try关闭它以忽略异常并且if出于某种原因......finallytry...catchNullPointerExceptionreadernull

据我所知,finally离开结构时总是会执行块try...catch,因此在块内返回一个值try仍然会finally在退出方法之前执行块......

这可以很容易地证明:

public static String test()
{
    String x = "a";
    try
    {
        x = "b";
        System.out.println("try block");
        return x;
    }
    finally
    {
        System.out.println("finally block");
    }
}

public static void main(String[] args)
{
    System.out.println("calling test()");
    String ret = test();
    System.out.println("test() returned "+ret);
}

结果是:

calling test()
try block
finally block
test() returned b

知道了这一切,为什么 Eclipse 会告诉我Resource leak: 'reader' is not closed at this location是否要在我的finally街区关闭它?


回答

我只想在这个答案中补充说他是正确的,如果new BufferedReader抛出异常,FileReader垃圾收集器销毁时会打开一个实例,因为它不会分配给任何变量,并且finally块不会关闭它,reader因为null.

这就是我修复这个可能的泄漏的方法:

@Override
public boolean isValid(File file) throws IOException
{
    FileReader fileReader = null;
    BufferedReader reader = null;
    try
    {
        fileReader = new FileReader(file);
        reader = new BufferedReader(fileReader);
        String line;
        while((line = reader.readLine()) != null)
        {
            line = line.trim();
            if(line.isEmpty())
                continue;
            if(line.startsWith("#") == false)
                return false;
            if(line.startsWith("#MLProperties"))
                return true;
        }
    }
    finally
    {
        try{reader.close();}catch(Exception e){}
        try{fileReader.close();}catch(Exception ee){}
    }
    return false;
}
4

4 回答 4

4

从技术上讲,有一条 BufferedReader 不会关闭的路径:如果reader.close()会抛出异常,因为您捕获了异常并且什么也不做。这可以通过reader.close()在您的 catch 块中再次添加来验证:

    } finally
    {
        try {
            reader.close();
        } catch (Exception e) {
            reader.close();
        }
    }

或者通过删除 finally 中的 try/catch:

    } finally
    {
            reader.close();
    }

这将使警告消失。

当然,它对你没有帮助。如果 reader.close() 失败,那么再次调用它没有意义。问题是,编译器不够聪明,无法处理这个问题。所以你能做的唯一明智的事情就是@SuppressWarnings("resource")在方法中添加一个。

编辑如果您使用的是 Java 7,您可以/应该做的是使用 try-with-resources 功能。这将使警告正确,并使您的代码更简单,为您节省一个finally块:

public boolean isValid(File file) throws IOException
{
  try(BufferedReader reader = new BufferedReader(new FileReader(file)))
  {
    String line;
    while ((line = reader.readLine()) != null)
    {
      line = line.trim();
      if (line.isEmpty())
        continue;
      if (line.startsWith("#") == false)
        return false;
      if (line.startsWith("#MLProperties"))
        return true;
    }
  } 
  return false;
}
于 2013-03-06T16:49:39.467 回答
3

如果BufferedReader构造函数抛出异常(例如内存不足),您将FileReader泄漏。

于 2013-03-06T16:50:02.307 回答
1
//If this line throws an exception, then neither the try block
    //nor the finally block will execute.
    //That is a good thing, since reader would be null.
    BufferedReader reader = new BufferedReader(new FileReader(aFileName));
    try {
      //Any exception in the try block will cause the finally block to execute
      String line = null;
      while ( (line = reader.readLine()) != null ) {
        //process the line...
      }
    }
    finally {
      //The reader object will never be null here.
      //This finally is only entered after the try block is 
      //entered. But, it's NOT POSSIBLE to enter the try block 
      //with a null reader object.
      reader.close();
    }
于 2013-03-06T16:49:54.023 回答
1

既然close()可以抛出异常(为什么哦,他们为什么要这样设计......)我倾向于使用双重尝试

try {
  BufferedReader reader = new BufferedReader(new FileReader(file));
  try {
    // do stuff with reader
  } finally {
    reader.close();
  }
} catch(IOException e) {
  // handle exceptions
}

由于这个习惯用法消除了 finally 块中的 try/catch,它可能足以让 Eclipse 满意。

new BufferedReader(...)本身不能抛出 an但从技术上讲,如果构造函数抛出or IOException,这仍然可能泄漏。FileReaderBufferedReaderRuntimeExceptionError

于 2013-03-06T16:54:45.537 回答