Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a good pattern for a java unit test that ensures that you are properly closing files?

I have an issue in my codebase where we are not properly closing file handles, or probably streams. We eventually get a TooManyOpenFiles exception under very heavy load. Based on the output of lsof, we are pretty sure we know where the leak is (in our logging system), but my question is: how can I write a unit test that checks, when it's complete, that resources have been closed properly? Is there a way to query the JRE to find out how many files are currently open? Can I somehow intercept file operations so I can monitor them?

I suspect I will have to instrument my code in order to manage all the file I/O, count references, and make sure they are getting closed that way, but if anyone knows of a top-down solution akin to those ideas I mentioned above, that would be a huge help!

like image 313
Mike Sokolov Avatar asked Sep 26 '11 17:09

Mike Sokolov


1 Answers

Since you are talking about Tests, PowerMock http://code.google.com/p/powermock/ might do the trick. It makes it possible to mock static methods and constructors if I am not mistaken. So you could mock/spy on the constructors and on the close methods or what ever you need for freeing the resources.

I try to avoid it in my tests but in the case which you describe it might be worth the hassle.

like image 108
Jens Schauder Avatar answered Oct 11 '22 12:10

Jens Schauder