Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a Javaagent to a JVM without stopping the JVM?

Tags:

I wish to profile a Java application without stopping the application. Can I add a Javaagent somehow while the application is running?

like image 963
yazz.com Avatar asked Jan 27 '11 14:01

yazz.com


People also ask

Can you have more than one Javaagent?

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> .

Where do I put Javaagent?

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.

What is Javaagent option?

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.


2 Answers

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.

like image 65
Vadzim Avatar answered Sep 23 '22 02:09

Vadzim


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!");     } } 
like image 30
Daniel Sperry Avatar answered Sep 26 '22 02:09

Daniel Sperry