开发者

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

I wish to profile a Java application without stopping the application. Can I add a Javaagent somehow 开发者_StackOverflowwhile the application is running?


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!");
    }
}


It should be possible according the documentation of the java.lang.instrument package.

Starting Agents After VM Startup

An implementation may provide a mechanism to start agents sometime after the the VM has started. The details as to how this is initiated are implementation specific but typically the application has already started and its main method has already been invoked. In cases where an implementation supports the starting of agents after the VM has started the following applies:

1.The manifest of the agent JAR must contain the attribute Agent-Class. The value of this attribute is the name of the agent class.
2. The agent class must implement a public static agentmain method.
3. The system class loader ( ClassLoader.getSystemClassLoader) must support a mechanism to add an agent JAR file to the system class path.

but I have never tried it :-|


Here a library that initializes aspectj and spring-aspects at runtime by injecting instrumentation: https://github.com/subes/invesdwin-instrument

You can use it as a more elaborate sample.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜