Java Is ByteArrayOutputStream safe without flush () and close ()?

Well, will a ByteArrayOutputStream cause a memory overflow if it doesn't close and close properly? I mean, should they be put into code or will Java be garbage-collecting it?

+11
source share
3 answers

No, he will receive garbage collection as soon as the last link to it is lost.

In javadoc :

Closing a ByteArrayOutputStream is not affected. Methods in this class can be called after the thread has been closed without throwing an IOException.

In addition, if you look at the code, then flush and close are not op-operations in the ByteArrayOutputStream class (although flush inherits from OutputStream , this does not work in OutputStream unless overridden in a particular implementation).

+11
source

Yes. It is safe not to flush() or not close() a ByteArrayOutputStream . and it doesn’t matter for memory usage whether you do it or not.

The only time that close() or flush() does anything in connection with a ByteArrayOuputStream , if you used it at the end of an output pipeline that includes a buffering component; e.g. BufferedWriter . Then you need to flush or close ... from the "top" of the pipeline ... to make sure that all data falls into the byte array.

GC makes no sense to call flush() or close() . In any case, the contents of the stream will remain in memory as long as the object remains reachable. (In contrast, read / write streams for external resources should be closed in a timely manner, since they have an external "resource descriptor" that needs to be freed ...)

Eventually:

  • This does not harm flush() or close() bare ByteArrayOutputStream . It is just not necessary.
  • It is often necessary to close an output pipeline that ends with a ByteArrayOutputStream , but this is not due to memory usage or GC considerations.
  • Memory is used (at least) as long as the ByteArrayOutputStream object is available.
+8
source

If you look at the source of ByteArrayOutputStream, you will see that the close and flush method is noop, which means that they really do nothing. However, I would recommend calling them, as it is possible that the implementation may change, although the behavior of the close method is explicitly specified in Javadoc.

Secondly, garbage collection has nothing to do with any of these methods. There are several different implementations (reference counting is one), but in general, when there are no more references to the object instance, garbage will be collected.

+1
source

All Articles