Search code examples
javajvmjavaagents

Attach to current VM using com.sun.tools


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?


Solution

  • 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