3

Is it possible to get the VM the program is currently running in? I know there is a VirtualMachine.list() method but I can't figure out how to find the right one. I can't search for a specific displayName since it's dynamic.

Is there another way to find the right VM?

Mario Codes
  • 689
  • 8
  • 15
ByteZ
  • 131
  • 1
  • 6
  • 1
    See the end of [this answer](https://stackoverflow.com/a/19912148/2711488) for a complete example. – Holger Sep 01 '20 at 07:12

1 Answers1

3

The ID of the VM to attach to is a process ID (pid). So, you just need to find pid of the current JVM process.

Here is a way to do this:

String jvmName = ManagementFactory.getRuntimeMXBean().getName();
String jvmPid = jvmName.substring(0, jvmName.indexOf('@'));

VirtualMachine self = VirtualMachine.attach(jvmPid);

Note: since JDK 9 attaching to current process requires setting the system property:

-Djdk.attach.allowAttachSelf=true
apangin
  • 92,924
  • 10
  • 193
  • 247