2014-10-09 21 views
1

我发现了Java API连接可以加载javaagent如下面的代码:的Java VirtualMachine.loadAgent只装剂在一次

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防止加载代理多次。

这是事实吗?为什么?

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

谢谢!

回答

2

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

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

loadAgent方法调用loadAgentLibrary它调用Agent_OnAttach这是平台特定

参考文献: