Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing a ByteArrayOutputStream has no effect?

Tags:

java

What does this statement, "Closing a ByteArrayOutputStream has no effect" (http://java.sun.com/javase/6/docs/api/java/io/ByteArrayOutputStream.html#close()) mean?

I want to make sure the memory in ByteArrayOutputStream gets released. Does ByteArrayOutputStream.close() really release the memory?

Thanks.

like image 776
user256239 Avatar asked Feb 24 '10 23:02

user256239


People also ask

Should ByteArrayOutputStream 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.

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).

Is ByteArrayOutputStream thread safe?

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

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

Does ByteArrayOutputStream.close() really release the memory?

No. It does absolutely nothing. You can look at its source code:

public void close() throws IOException { } 

To release the memory, make sure there are no references to it and let the Garbage Collector do its thing. Just like with any other normal object.

File- and Socket-based streams are special because they use non-memory OS resources (file handles) that you can run out of independantly of memory. That's why closing them explicitly is important. But this does not apply to the purely memory-based ByteArrayOutputStream.

like image 169
Michael Borgwardt Avatar answered Oct 15 '22 15:10

Michael Borgwardt