简体   繁体   English

有没有一种可移植的方法来从虚拟机内部找出JVM打开了多少文件?

[英]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. 我正在为一些Java文件处理代码编写测试,并希望确保正确关闭所有文件。 I don't want to run 'lsof' as that will open more files and make the test suite non-portable. 我不想运行“ lsof”,因为那样会打开更多文件并使测试套件不可移植。 Anyone know a way to do this? 有人知道这样做的方法吗?

If you're looking for something that's part of the JDK, the answer is no. 如果您正在寻找JDK的一部分,答案是否定的。

You might find something that uses JVMTI , but that wouldn't be portable (it's a native interface). 您可能会发现一些使用JVMTI的东西,但这不是可移植的(这是一个本机接口)。 Or something that uses JPDA , but that would require a second JVM. 或使用JPDA的东西,但需要第二个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. 如果你想在-JVM上运行,并随身携带,你必须引入一个工厂为您的文件引用:全部更换new FileInputStream() new FileOutputStream() new RandomAccessFile() new FileReadernew FileWriter与电话该工厂对象上的方法。 This factory will return subclasses of these objects, that have the close() method overridden. 该工厂将返回这些对象的子类,这些子类的close()方法被覆盖。 It will also increment an "open files" counter, that is then decremented by the overridden close() . 它还将增加一个“打开文件”计数器,然后由覆盖的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. 工厂方法和计数器将需要是静态的和同步的(除非您想注入工厂),并且应使用系统属性来确定是返回子类流还是JDK版本。

Personally, I'd take the advice in the comment, and use FindBugs first. 就个人而言,我会在注释中接受建议,并首先使用FindBugs。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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