Is there a portable way to find out how many JVM files are open from inside the virtual machine?

I am writing tests for some Java file processing code and want to make sure all files are closed properly. I do not want to run "lsof", as this will open more files and make the test suite not portable. Does anyone know a way to do this?

+8
java unit-testing junit jvm
source share
1 answer

If you are looking for some part of the JDK, the answer will be no.

You may find something that uses the JVMTI , but it will not be portable (this is a native interface). Or something that uses JPDA , but that will require a second JVM. I give you these two abbreviations as a start for Google.

If you want to run in-JVM and be portable, you will have to enter factory for file references: replace all new FileInputStream() , new FileOutputStream() , new RandomAccessFile() , new FileReader and new FileWriter calls methods on this factory object. This factory will return subclasses of these objects for which the close() method is overridden. It will also increment the "open files" counter, which will then decrease with the redefined close() .

The methods and factory counter should be static and synchronized (if you do not want to embed a factory) and should use the system property to decide whether to return subclasses or the JDK version.

Personally, I would recommend in a comment and use FindBugs first.

+2
source share

All Articles