2

I use a ByteArrayOutputStream to fill a byte array with different values of different length in bytes. I use the method write(byte[] b). As this method is inherited from OutputStream it could throw an IOException. In ByteArrayOutputStream there is a method write(byte[] b, int off, int len) which don't throw an IOException, so I extend ByteArrayOutputStream and override the write(byte[] b) method which now also don't throw an IOException:

  private class ByteArrayOutputStreamNoException extends ByteArrayOutputStream
  {

      public ByteArrayOutputStreamNoException(int size)
      {
          super(size);
      }

      public ByteArrayOutputStreamNoException()
      {
          super();
      }

      @Override
      public void write(byte[] data)
      {
          write(data, 0, data.length);
      }
  }

With the extended class I get now in eclipse 4.5.1 a warning of a resource leak, as I don't close the stream in the code. This was not the case with ByteArrayOutputStream. What is wrong with my extended class or what do I have to add to it to remove the warning? I know I could add the SuppressWarnings annotation to each instantiation of the stream but I prefer to change the extended class somehow to remove the warning.

2
  • Which version of java is this ? I copied it and it didnt show any warnings for jdk 1.8 Dec 9, 2015 at 9:29
  • I use also jdk 1.8.0_66. Then its maybe eclipse?
    – Semaphor
    Dec 9, 2015 at 9:37

1 Answer 1

3

Eclipse has a list of classes in the standard Java libraries which are known not to need the resource leak warning, ByteArrayOutputStream is one of these. There is a long description of this in Eclipse bug 358903.

The code implementing this is the applyCloseableClassWhitelists method of org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding. The list of classes is hard coded and cannot be extended.

When you extend the ByteArrayOutputStream class Eclipse can no longer be sure that the close is not needed so you get the warning.

You could use the 'try-with-resources' style try statement to work around this:

try
 (ByteArrayOutputStreamNoException stream = new ByteArrayOutputStreamNoException())
 {
   // TODO work with the stream
 } 
1
  • Ok, didn't know that these classes are hardcoded in eclipse, thanks. In this case, I will maybe use the @SuppressWarnings annotation nonetheless.
    – Semaphor
    Dec 9, 2015 at 10:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.