I\'m using the attach API to load a JVMTI agent at runtime. I\'d like to unload the JVMTI agent when my program is done without terminating the JVM the agent is loaded in. A
You have to load JVMTI agent programatically :
// attach to target VM
VirtualMachine vm = VirtualMachine.attach("2177");
// get system properties in target VM
Properties props = vm.getSystemProperties();
// construct path to management agent
String home = props.getProperty("java.home");
String agent = home + File.separator + "lib" + File.separator
+ "your-agent-example.jar";
// load agent into target VM
vm.loadAgent(agent, "com.sun.management.jmxremote.port=5000");
// detach
vm.detach();
see doc here
After that you have to use a different classLoad than default :
You have to set the system property "java.system.class.loader" to be the name of your custom class loader for your target JVM.
see doc here
"Java's builtin Class loaders always checks if a class is already loaded before loading it. Reloading the class is therefore not possible using Java's builtin class loaders. To reload a class you will have to implement your own ClassLoader subclass."
In your case you have to implement a ClassLoader which has ClassLoader.getSystemClassLoader() has parent.
"Even with a custom subclass of ClassLoader you have a challenge. Every loaded class needs to be linked. This is done using the ClassLoader.resolve() method. This method is final, and thus cannot be overridden in your ClassLoader subclass. The resolve() method will not allow any given ClassLoader instance to link the same class twice. Therefore, everytime you want to reload a class you must use a new instance of your ClassLoader subclass. This is not impossible, but necessary to know when designing for class reloading."
see Dynamic Class Reloading
JVMTI spec says unloading (without JVM termination) is possible, but platform-dependent and out of specification's scope.