Question

I don't understand. For example We have an variable of OutputStream type in a code, we should call close() on it when we stop using it, well why it wasn't implemented this way: GC calls close() itself when it does a clean up of this variable?

Update: ok What I've concluded so far: releasing unmanaged recourses is not only about releasing memory what is more important that we don't now internal behavior behind it, it could exists a limitation on amount of this resource(number of connections/handlers) that's why we need to free them as soon as possible. Am I right? Because if it's all about the memory then I don't know why GC can't do the job just the way it does with managed recourses.

Was it helpful?

Solution

close will in most cases eventually be called automatically by the GC through the finalize method (any class can have such finalize that is called by the GC when destroying the object; for Closable types that hold resources it will generally be implemented to call close). The issue of course is that you just don't have control over when this happens (if ever). It could be 10 sec or 10 min from when you stopped needing the object, still using up whatever resource was allocated. So it's good style to clean up your resource handles once you don't need them anymore.

Also, since Java 7 you can actually do this:

try (BufferedReader br =
               new BufferedReader(new FileReader(path))) {
    return br.readLine();
}

And close will be called automatically at the end of the try block.

See the documentation for more details.

And finally, to the why there is Closable and things that need explicit closing in the first place, this is for resources that are not directly managed by the JVM and can hence also not automatically be reclaimed by GC. Such resources are for instances files, sockets or audio output.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top