3

Considering Java code below:

void test(InputStream inputStream) {
    DataInputStream dataInputStream = new DataInputStream(inputStream);
    return;
}

when test method returns, dataInputStream will (sometime) be garbage collected. Does DataInputStream closes inner stream in its finalizer?

I failed to find any explicit statement if it does or not. Is there any official documentation about behavior? Can please you point if there is one?

Thanks.

Edit: I am not asking if closing DataInputStream closes inner stream too. I am asking what if I don't close and outer stream is garbage collected while inner still has references to it hence alive.

volkan
  • 153
  • 2
  • 11
  • 2
    @tunaki the OP asked if the stream will be closed without an explicit close call because of a GC finalizer - and the answer is no, since there is no such finalizer – wero May 01 '16 at 19:28
  • @wero Yes, that's what I ask. Is "No such finalizer" documented in some place? Is it implementation specific or mandatory by specification? Any links? Thanks. – volkan May 01 '16 at 19:39
  • 3
    @Volkan simply look at the source of `DataInputStream` and work up the hierarchy - there is no finalizer. The only classes in `java.io` with a finalizer are `FileInputStream` and `FileOutputStream`. Don't know if that is document anywhere. – wero May 01 '16 at 19:45

1 Answers1

1

There is no documentation saying explicitely that the DataInputStream hasn’t a finalizer, but you could fill books with what a class doesn’t do. Since the purpose of a finalize() method is to release a resource a broken program forgot to release, only classes bearing a resource may have such a safety net. But DataInputStream doesn’t hold a resource, hence, hasn’t such a finalize() method.

It’s the underlying InputStream which might hold a resource and hence, only when the underlying InputStream becomes unreachable, a guarding cleaner may release the resource. It can be surely considered broken behavior when code outside your control spuriously closes your InputStream while you are still holding a strong reference to it.

Holger
  • 285,553
  • 42
  • 434
  • 765