最近在学习、了解一些JVM方面的知识,遇到了VisualVM、Jps等一些JVM分析工具都不显示本地运行中的Java进程的问题,分享一下希望能帮助遇到同样问题的各位,以下是我的出现问题时的运行环境:

  • Windows10系统
  • Jdk 11
  • 使用IDEA运行的Java程序

VisualVM故障排除指南

因为VisualVM也不能正常的显示运行中的Java进程,所以首先我查看了VisualVM的故障排除指南,其中提示到:

Local Applications Cannot Be Detected (Error Dialog On Startup)

Description: An error dialog saying that local applications cannot be detected is shown immediately after VisualVM startup.

Resolution: This can happen on Windows systems, it’s caused by misconfigured jvmstat technology used to detect the running applications. There are two possible causes:

  • Insufficient permissions for %TMP%\hsperfdata_username folder - make sure you’re able to create a file in the directory and eventually update the permissions for full folder access. Alternatively you can just re-create the folder which should automatically set the correct access rights. See see this forums.sun.com thread for more details.
  • Having %TMP%\hsperfdata_username folder on a FAT disk - by default jvmstat doesn’t work on FAT disks due to security restrictions. You can bypass the security check by setting the -XX:+PerfBypassFileSystemCheck flag for both VisualVM and the monitored application. See the JDK bug #5042659 for more details.

Local Applications Cannot Be Monitored (Error Dialog On Startup)

Description: An error dialog saying that local applications cannot be monitored is shown immediately after VisualVM startup. Locally running Java applications are displayed as (pid ###).

Resolution: This can happen on Windows systems if the username contains capitalized letters. In this case, username is UserName but the jvmstat directory created by JDK is %TMP%\hsperfdata_username. To workaround the problem, exit all Java applications, delete the %TMP%\hsperfdata_username directory and create new %TMP%\hsperfdata_UserName directory.

从中我们可以了解到,Windows系统下VisualVM对Java程序的运行监控依赖于%TMP%\hsperfdata_username文件夹下的文件(TMP配置于环境变量、hsperfdata_username 中的username 为电脑用户名)

实际运行Java程序时会在上文提到的%TMP%\hsperfdata_username文件夹下生成一个文件名为纯数字的文件,这个数字实际上就是你在JPS下看到的进程是对应的,所以你可能需要进行检查:

  • 检查你的操作系统环境变量中的 TMP是否正确进行配置
    image-20230307042251235

  • 检查%TMP%\hsperfdata_username文件夹是否存在,当前用户是否有权限对此文件夹进行操作
    image-20230307042328733

  • 系统用户名是否为中文,非中文路径可能产生许多奇奇怪怪的问题

所以你可以尝试退出所有 Java 应用程序后(IDEA、Eclipse、VisualVM都是),然后删除%TMP%\hsperfdata_username 目录并创建新的%TMP%\hsperfdata_UserName目录或者检查、修改%TMP%\hsperfdata_username为正确的用户权限;

如果是使用IDEA运行的,你还可以尝试右键使用管理员模式运行IDEA;

确保如果进行了上面的操作后如果还是无法正常显示,可能需要从其他角度排查问题,请尝试使用完全相同的环境打印Java程序运行时获取到的TMP环境变量,如下:

System.out.println(System.getenv("tmp"));

或者输出全部环境变量:

System.out.println(System.getenv());

正常情况应该输出你系统中配置的环境变量中的 /tmp文件路径,如果tmp项输出为null,则问题在运行的Java程序没有获取到你的环境变量,如果是使用idea运行的,请检查idea的运行配置是否包含了系统环境变量
image-20230307045645285

至此我的问题解决啦,希望也能对你提供一些排查思路!