How to avoide a "potential resource leak" warning when using explicit constructor invocation?

Viewed 84

In my old code, I often used the following constructor idiom for convenience:

MyClass( InputStream input ) {
  // do actual stuff
}
MyClass( String filename ) {
  this( new FileInputStream(filename) )
}

This leads to Eclipse warning me of a "Potential resource leak: '<unassigned Closeable value>' may not be closed" in the explicit constructor invocation.

Usually, I would use a try-with block for the auto-closable FileInputStream, but this is not possible here since the invocation must always be the first statement in a constructor. That is, the following does not compile:

MyClass( InputStream input ) {
  // do actual stuff
}
MyClass( String filename ) {
  try( FileInputStream fis = new FileInputStream(filename) ) {
    this( fis );
  }
}

So, what would be the correct (and elegant?) way to use this idiom without the risk of a potential resource leak? Any help is appreciated.

1 Answers

Even if you could wrap the constructor call in a try-with-resources, does it really make sense? The constructor is most likely storing the InputStream in some internal state, so closing it in the constructor makes it invalid when subsequently used in other methods of the class.

A better solution is to make MyClass implement AutoCloseable and close the input stream in the close() method, hence giving users of your class control over how to close the input stream that is passed to the MyClass instance.

Related