Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Simple snippet to show how to attach javaagent to running JVM process
import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;
public class AgentRunner {
/*
* This class shows how to attach hotswap-agent.jar to a running JVM process and overload classes using "extraClasspath=" property via Hotswapper plugin.
*
* Lets assume that:
* args[0] contains pid of running JVM process or a runner class name we want to attach agent to
* args[1] contains absolute path to agent.jar
* args[2] contains parameters needed to pass to agent
*/
public static void main(String[] args) {
if (2 > args.length) {
System.out.println("Usage: java -cp .:$JAVA_HOME/lib/tools.jar AgentRunner JVM_PID_OR_NAME PATH_TO_JAR [PARAMS]");
} else try {
String pid = args[0];
for (VirtualMachineDescriptor vmd : VirtualMachine.list()) {
if (vmd.displayName().contains(args[1])) {
pid = vmd.id();
break;
}
}
final VirtualMachine vm = VirtualMachine.attach(pid);
vm.loadAgent(args[1], 3 > args.length || null == args[2] ? "" : args[2]);
vm.detach();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment