简体   繁体   中英

Detecting and handling third-party library filehandle leaks in Java

Is there any way to detect and handle whether a Java library is correctly releasing file-handles (via "close") from within a Java program that is using said library, short of having access to the actual library code and inserting the corresponding "finally close" statements?

If detection is feasible, is there any way to close those file-handles without a reference to the Reader (or FileInputStream) that was reading the file?

I think that Kohsuke's file leak detector is very close to what was asked (almost 4 years ago). It is a Java agent "that keeps track of where/when/who opened files in your JVM. You can have the agent trace these operations to find out about the access pattern or handle leaks, and dump the list of currently open files and where/when/who opened them". More info in the link above.

Under Linux and probably some Unixes, you can use lsof to "list open files" opened by an application. You'll probably see their number increase if your app is leaking file handles. You may even hit the (default) ceiling of 1024 handles eventually.

Under Windows, there's some free similar utilities somewhere in the SysInternals suite; I think it's called "handles" or "fhandles" or such. I'll go see if I can find it...


EDIT: Ah, here it is: Handle .


EDIT: I recently ran into a similar, obscure problem with sockets (which are also a kind of file handle, at least under Linux): Turns out that even if the connection was closed, the associated file handles would not be released until Java did a garbage collection. Our app didn't go through a lot of memory, so often connection handles would pile up faster than they got cleaned up. We solved the problem by inserting a System.gc() every once in a while. The performance hit was tolerable relative to an out-and-out malfunction when the app ran out of handles.


EDIT: At its higher level, the JRE's library is of course "just" Java code, and the source code is AFAIK still being published. So if you're really desparate, you could write your own wrappers around things like FileInputStream and FileReader , etc. I believe there's a directory name in the JRE's file tree into which you can put Jars of "fiddled" classes; it's called "endorsed" or something like that. That, or you could out-and-out make source code changes to the JRE library code and build your own replacment jars for the Sun (or whatever) libraries. This is obviously not clean or highly portable. I don't have any experience of my own with such measures, nor would I recommend them.

您可以在库上运行FindBugs。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM