【问题标题】:Java VirtualMachine.loadAgent only load agent at onceJava VirtualMachine.loadAgent 一次只加载代理
【发布时间】:2014-10-09 09:57:32
【问题描述】:

我发现 Java attach API 可以加载 javaagent,如下代码:

import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;
import java.util.List;

public class ListVM{
  public static void main(String[] args){
        List<VirtualMachineDescriptor> vmList = VirtualMachine.list();
        for(VirtualMachineDescriptor vm : vmList){
        System.out.println("name: " + vm.displayName() + " id :" + vm.id());
        try{
            VirtualMachine vm0 = VirtualMachine.attach(vm.id());
            // load agent, agnet class's agentmain will be invoked. 
            vm0.loadAgent("/root/tmp/ChinaAgent.jar");
            System.out.println("Load agent done.");
            vm0.detach();
        }catch(Exception e) {
            System.out.println("exception : " + e.getMessage());
        }
        }
  }
}

声明:vm0.loadAgent("/root/tmp/ChinaAgent.jar"); 加载代理 jar 文件。

但是代理的代码只会运行一次,

所以我猜代理 jar 只加载了一次,这意味着 Jvm 会阻止多次加载代理。

这是真的吗?为什么?

希望能有一些代码来证明!

谢谢!

【问题讨论】:

    标签: java jvm jvm-hotspot


    【解决方案1】:

    代理 jar 在您调用 loadAgent 时运行一次。 JAR 清单中Agent-Class 属性指定的代理类的agentmain 方法被调用。

    该类实际上只加载一次,除非您对卸载类进行了一些优化。因此,如果您在同一个 jar 上多次调用 loadAgent,则不会重新加载类,但可能会多次调用 Agent_OnAttach (agentmain)。 实际上它是特定于平台的,并且取决于 JVM 实现。

    loadAgent 方法调用 loadAgentLibrary,后者调用特定于平台的 Agent_OnAttach

    参考资料:

    【讨论】:

      猜你喜欢
      • 2011-04-12
      • 2011-09-15
      • 1970-01-01
      • 1970-01-01
      • 2022-08-23
      • 1970-01-01
      • 2019-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多