Freeing java file handles

后端 未结 3 1561
庸人自扰
庸人自扰 2021-01-25 08:18

We have a rather large and complex application written in Java which is running on top of the Gridgain package. The problem I am having is that this application will sit there p

相关标签:
3条回答
  • 2021-01-25 08:44

    There is little point in overriding finalize(). If the handle is getting garbage collected and finalized, then so is the instance of java.io.BufferedReader and it will get closed.

    It is possible (according to the spec) that the handle is being garbage collected but not finalized, but this is not very likely.

    You could try using PhantomReferences to clean up unused file handles, but my guess is that your instances of BufferedReaderImpl are still referenced from somewhere (e.g. values in a Map from filenames to open handles) and that is what is preventing them from being closed (in which case finalizers will not help.)

    0 讨论(0)
  • 2021-01-25 08:45

    Java specification says that it is not guarantee that 'finalize()' will be executed. Your code must explicitly close FileReader yourself.

    0 讨论(0)
  • 2021-01-25 08:46

    Finalizers can't be relied on to be called. It's not a good approach for resource management. The standard construct in Java for this is:

    InputStream in = null;
    try {
      in = ...;
      // do stuff
    } catch (IOException e) {
      // error
    } finally {
      if (in != null) { try { in.close(); } catch (Exception e) { } }
      in = null;
    }
    

    You may want to wrap these handles inside a class but that's not a robust approach.

    0 讨论(0)
提交回复
热议问题