Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does argument/parameters InputStream need to be closed in android?

All stream and bufferedReader need to be closed my question is what if the stream and bufferedReader is inside a method arguments/parameters need to be closed also?

example normal code:

InputStream i = entity.getContent();
i.close();

Q: What if its inside an arguments of a method that has been pass only

public void doDownload(InputStream i, BufferedReader b) {
    i.close();
    b.close();
}

should i also close it even that inputstream and bufferedreader is only an arguments and don't have an Object?

like image 749
Piolo Opaw Avatar asked May 29 '14 03:05

Piolo Opaw


1 Answers

This is (mostly) a matter of style, as long as someone closes them. However, a consistent approach works best. The key technique to manage this kind of resources is to make their ownership clear: the owner of the resource is responsible for releasing it. This ownership can change during the lifetime of the resource, but it should be clear at any point.

In this case:

public void doDownload(InputStream i, BufferedReader b) { ... }

the stream and reader was not created by this method, but was rather provided to it. Therefore, it is the caller who should be responsible for closing it. It may even continue using the resource after this method finishes executing, so it should not be closed.

However, in some cases, calling a method may be a form of transferring ownership of the resource. A clear example of this is stream chaining in Java -- creating an OuputStream by wrapping another OutputStream means the outer one is now responsible for closing the inner one when it's closed itself.

In the other example:

InputStream i = entity.getContent();

it depends on a subtle difference. Did the getContent() method actually create the InputStream, or just obtain a reference to a resource that actually belongs to the entity object? In the first case, then the caller method should be responsible for releasing it. Otherwise, the Entity class should do itself (as per the RAII pattern).

A more clear example would be:

InputStream i = context.openFileInput(fileName);

In this case, the caller is clearly responsible for the creation of the InputStream, and therefore is responsible for closing it.

like image 158
matiash Avatar answered Sep 20 '22 22:09

matiash