Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a portable way to find out how many files a JVM has open from inside the VM?

I am writing tests for some Java file handling code and want to make sure all files are closed properly. I don't want to run 'lsof' as that will open more files and make the test suite non-portable. Anyone know a way to do this?

like image 718
David Tinker Avatar asked Oct 30 '12 17:10

David Tinker


1 Answers

If you're looking for something that's part of the JDK, the answer is no.

You might find something that uses JVMTI, but that wouldn't be portable (it's a native interface). Or something that uses JPDA, but that would require a second JVM. I give you those two acronyms as a start for Googling.

If you want to run in-JVM and be portable, you'll have to introduce a factory for your file references: replace all new FileInputStream(), new FileOutputStream(), new RandomAccessFile(), new FileReader, and new FileWriter calls with methods on that factory object. This factory will return subclasses of these objects, that have the close() method overridden. It will also increment an "open files" counter, that is then decremented by the overridden close().

The factory methods and counter will need to be static and synchronized (unless you want to inject the factory), and should use a system property to decide whether to return a subclassed stream or the JDK version.

Personally, I'd take the advice in the comment, and use FindBugs first.

like image 93
kdgregory Avatar answered Oct 23 '22 04:10

kdgregory