I have a program which requires dynamically (i.e. at run time) opening an available socket and start a JMX agent on it. This JMX parameters are being set inside the Java cod
kbec's answer showed the way but did not work for me - however by looking at this post I was able to modify it and get a working solution.
public static String loadJMXAgent(int port) throws IOException,
AttachNotSupportedException, AgentLoadException,
AgentInitializationException {
String name = ManagementFactory.getRuntimeMXBean().getName();
VirtualMachine vm = VirtualMachine.attach(name.substring(0,
name.indexOf('@')));
String lca = vm.getAgentProperties().getProperty(
"com.sun.management.jmxremote.localConnectorAddress");
if (lca == null) {
Path p = Paths.get(System.getProperty("java.home")).normalize();
if (!"jre".equals(p.getName(p.getNameCount() - 1).toString()
.toLowerCase())) {
p = p.resolve("jre");
}
File f = p.resolve("lib").resolve("management-agent.jar").toFile();
if (!f.exists()) {
throw new IOException("Management agent not found");
}
String options = String.format("com.sun.management.jmxremote.port=%d, " +
"com.sun.management.jmxremote.authenticate=false, " +
"com.sun.management.jmxremote.ssl=false", port);
vm.loadAgent(f.getCanonicalPath(), options);
lca = vm.getAgentProperties().getProperty(
"com.sun.management.jmxremote.localConnectorAddress");
}
vm.detach();
return lca;
}
This works in Eclipse however getting it to work at the command line is a different matter - there is some discussion about this here Why does using the Java Attach API fail on linux? (even though maven build completes) but I found adding $JAVA_HOME/lib/tools.jar to my classpath solved the problem.