Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

Well, will ByteArrayOutputStream cause memory overflow if it doesn't properly flush and close? I mean are they necessary to be put in the code or Java will garbage-collect it?

like image 559
lannyboy Avatar asked Apr 19 '14 01:04

lannyboy


People also ask

Does ByteArrayOutputStream need to be closed?

Closing a ByteArrayOutputStream has no effect. The methods in this class can be called after the stream has been closed without generating an IOException.

Is ByteArrayOutputStream thread safe?

Yes it is thread safe, or rather all its methods are synchronized, and ProcessBuilder.

Does ByteArrayInputStream need to be closed?

You don't have to close ByteArrayInputStream , the moment it is not referenced by any variable, garbage collector will release the stream and somebytes (of course assuming they aren't referenced somewhere else).

What is the use of ByteArrayOutputStream in Java?

The ByteArrayOutputStream class of the java.io package can be used to write an array of output data (in bytes). It extends the OutputStream abstract class. Note: In ByteArrayOutputStream maintains an internal array of bytes to store the data.


1 Answers

No, it will get garbage collected once the last reference to it is lost.

Per the javadoc:

Closing a ByteArrayOutputStream has no effect. The methods in this class can be called after the stream has been closed without generating an IOException.

Also, if you look at the code, both flush and close are no-ops in the ByteArrayOutputStream class (although flush is inherited from OutputStream, it is a no-op in OutputStream unless overridden in the specific implementation).

like image 145
Shadow Man Avatar answered Oct 02 '22 19:10

Shadow Man