71

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.

ChrisN
  • 16,635
  • 9
  • 57
  • 81
user256239
  • 17,717
  • 26
  • 77
  • 89

2 Answers2

131

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.

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
-1

When you call close() on a ByteArrayOutputStream, it will release any system resources associated with the stream. This includes flushing any buffered data to the underlying byte array and closing the stream. After calling close(), any further attempts to write to the stream will result in an IOException.

If you do not call close() explicitly, the stream will still be closed automatically when the garbage collector finalizes the object. However, relying on the garbage collector to close the stream is not recommended, as it can lead to resource leaks and unexpected behavior.

It is good practice to always call close() on output streams when you are done using them, to ensure that any buffered data is written and the resources are properly released. This is particularly important if you are working with streams that interact with external resources, such as files or network sockets.

Sandeep Patel
  • 2,069
  • 2
  • 14
  • 20