Chinaxing
Chinaxing

Reputation: 8874

Java VirtualMachine.loadAgent only load agent at once

I found the Java attach API can load the javaagent as following code :

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());
        }
        }
  }
}

the statement : vm0.loadAgent("/root/tmp/ChinaAgent.jar"); which load the agent jar file.

but the Agent's code will only be run once,

so i guess the Agent jar was loaded only once, which means The Jvm prevent load a agent multiple times.

is this the truth ? why ?

hope can have some code to prove it !

thanks !

Upvotes: 1

Views: 3469

Answers (1)

alain.janinm
alain.janinm

Reputation: 20065

The agent jar is run once when you call loadAgent. The agentmain method of the agent class specified by the Agent-Class attribute in the JAR manifest is invoked.

The class is actually loaded once, except if you have done some optimization to unload classes. So if you call loadAgent multiple time on the same jar, the classes would not be reloaded but the Agent_OnAttach (agentmain) might be called multiple time. Actually it's platform specific and depends on the JVM implementation.

The loadAgent method calls loadAgentLibrary which calls Agent_OnAttach which is platform specific

References :

  • VirtualMachine API
  • java.lang.instrument
  • JVMTI
  • HotSpotVirtualMachine#loadAgent(String, String) source code (The HotSpot implementation of com.sun.tools.attach.VirtualMachine), take a look in hierarchy tab to see the BSD, Linux, Solaris and Windows implementation. These classes end up calling native methods. You can find them if you download openJDK source for example for windows, it will use jdk\src\windows\native\sun\tools\attach\WindowsVirtualMachine.c file

Upvotes: 2

Related Questions