Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 560
ByteZ Avatar asked Aug 26 '26 19:08

ByteZ


1 Answers

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
like image 114
apangin Avatar answered Aug 29 '26 09:08

apangin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!