• Post Reply Bookmark Topic Watch Topic
  • New Topic

InputStream.close() vs garbage collection  RSS feed

 
Majid Al-Fifi
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

If within a method, an InputStream object is created and is used to read some file, why do we usually call close() when done.

isn't InputStream object going to be garbage-collected anyway?
 
Joe Ess
Bartender
Posts: 9429
12
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Garbage collection will only free the resources within the JVM. The resources assigned to the VM by the operating system will still be reserved. I've seen several poorly written applications run out of resources due to poorly handled database connections, sockets and files. Rule of thumb: if it has a close() method, invoke it when you are done with it. And invoke it in a finally block so it will be called even if an exception occurs.
 
Vlado Zajac
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Garbage collection frees Java heap (memory) but close frees OS resources used for open file (number of open files is limited on most system) and assures that the data is really written.

GC only automaticaly manages memory not open files.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, many classes such as FileInputStream and RandomAccessFile are written with a finalize() method which ensures that IF an instance in garbage collected, close() will be called first. So in many cases, garbage collection does indirectly free up files, and it is often possible for programmers to be lazy about closing resources, because garbage collection usually cleans them up for you. Unfortunately.

The problem is that you can't control when this happens, and it may not happen at all. So if you have too many files open, the operating system may give you an error about that before the garbage collector gets around to closing them. Or if you want to move a file or delete it, immediately after reading it - the move or delete may fail, because at that moment you've still got the file open for reading.

Errors like this are often hard to reproduce reliably, because they depend on the timing of the garbage collector. So you get things which usually work fine, but sometimes fail mysteriously. Very annoying to debug. For this reason, it is stronly recommended to be sure to close() any stream/reader/connection or other closable resource you may be using, as soon as you are done with it. Preferably in a finally block, to ensure it happens even if some other error occurs in processing.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!