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?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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, andnew FileWritercalls with methods on that factory object. This factory will return subclasses of these objects, that have theclose()method overridden. It will also increment an “open files” counter, that is then decremented by the overriddenclose().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.