Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

garbage collection - Will stream classes or connections considered as a resource leak in Java

Java has no lifetime for an object, this is managed by the garbage collector. And if I use some IO classes without closing it, or some DBConnection, will this considered a resource leak? In another words, will IO object be collected and destroyed by garbage collector, AFAIK, the garbage collector is for memory only. For example:

BufferedReader br = new BufferedReader( new FileReader( new File("path") ) );
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes you are right.

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.

But 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.

And with Java 7, there is an addition of AutoClosable interface, read more about it here.

Ref: http://www.coderanch.com/t/278165//java/InputStream-close-garbage-collection


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...