如何找出Java应用程序当前打开的文件数量? [英] How to find out number of files currently open by Java application?

查看:681
本文介绍了如何找出Java应用程序当前打开的文件数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您的应用程序执行的很多操作都涉及读取文件的内容。不言而喻,打开然后关闭的文件和生活是好的,除非..新文件进入速度更快,然后旧文件关闭。这是我发现自己处境的一种情况。

Suppose a lot of what your application does deals with reading contents of the files. Goes without saying that files that are open then closed and life is good unless .. new files come in faster then old files get closed. This is the pickle of a situation i found myself in.

现在..有没有办法可靠地知道流程打开了多少文件?与查看 ls / proc / my_pid / fd |一样可靠的东西wc -l <​​/ code>来自JVM内部?

Now .. is there a way to reliably know how many files are open by the process? Something that as reliable as looking at ls /proc/my_pid/fd | wc -l from inside the JVM?

我怀疑答案可能是特定于操作系统的,所以让我补充一点,我在Linux上运行Java。

I suspect answer may be OS specific, so let me add that i am running Java on Linux.

推荐答案

在unix上,一种方法是使用 ManagementFactory 获取 OperatingSystemMxBean 如果是 UnixOperatingSystemMXBean 您可以使用 getOpenFileDescriptorCount()方法。

On unix one way is using the ManagementFactory to get the OperatingSystemMxBean and if it is a UnixOperatingSystemMXBean you can use getOpenFileDescriptorCount() method.

以下示例代码

import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import com.sun.management.UnixOperatingSystemMXBean;
public class OpenFileCount{
    public static void main(String[] args){
        OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
        if(os instanceof UnixOperatingSystemMXBean){
            System.out.println("Number of open fd: " + ((UnixOperatingSystemMXBean) os).getOpenFileDescriptorCount());
        }
    }
}

这篇关于如何找出Java应用程序当前打开的文件数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆