I wish to profile a Java application without stopping the application. Can I add a Javaagent somehow while the application is running?
The -javaagent option may be used multiple times on the same command-line, thus starting multiple agents. The premain methods will be called in the order that the agents are specified on the command line. More than one agent may use the same <jarpath> .
To pass the -javaagent argument on WebSphere: From the admin console, select Servers > Application servers > (select a server) > Configuration > Service Infrastructure > Java and Process Management. Select Process Definition > Additional Properties, then select Java Virtual Machine. Select Apply, then select Save.
Java agents are a special type of class which, by using the Java Instrumentation API, can intercept applications running on the JVM, modifying their bytecode.
See Starting a Java agent after program start.
It links to http://dhruba.name/2010/02/07/creation-dynamic-loading-and-instrumentation-with-javaagents/ that under "Dynamic loading of a javaagent at runtime" provides working example:
public static void loadAgent() throws Exception { String nameOfRunningVM = ManagementFactory.getRuntimeMXBean().getName(); String pid = nameOfRunningVM.substring(0, nameOfRunningVM.indexOf('@')); VirtualMachine vm = VirtualMachine.attach(pid); vm.loadAgent(jarFilePath, ""); vm.detach(); }
Note that Java 9 requires -Djdk.attach.allowAttachSelf=true
to be present among JVM startup arguments.
You can use ea-agent-loader
With it loading an agent in runtime will look like:
public class HelloAgentWorld { public static class HelloAgent { public static void agentmain(String agentArgs, Instrumentation inst) { System.out.println(agentArgs); System.out.println("Hi from the agent!"); System.out.println("I've got instrumentation!: " + inst); } } public static void main(String[] args) { AgentLoader.loadAgentClass(HelloAgent.class.getName(), "Hello!"); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With