I'm working on a monitoring application, which uses Sigar for monitoring to monitor different kind of applications. One problem with Sigar is that when monitoring the heap usage of a Java application (JVM) I only get the maximum heap size but not the actually used heap size of the JVM. So I extended my monitoring application to use JMX to connect to a JVM and retrieve the CPU as well as the heap usage. This works fine so far, but I want to automise everything as much as possible and I don't want to start all my applications, being monitored, with JMX activated, but activate it dynamically when needed with the following piece of code:
private void connectToJVM(final String pid) throws IOException, AgentLoadException, AgentInitializationException {
List<VirtualMachineDescriptor> vms = VirtualMachine.list();
for (VirtualMachineDescriptor desc : vms) {
if (!desc.id().equals(pid)) {
continue;
}
VirtualMachine vm;
try {
vm = VirtualMachine.attach(desc);
} catch (AttachNotSupportedException e) {
continue;
}
Properties props = vm.getAgentProperties();
String connectorAddress = props.getProperty(CONNECTOR_ADDRESS);
if (connectorAddress == null) {
String agent = vm.getSystemProperties().getProperty("java.home") + File.separator + "lib"
+ File.separator + "management-agent.jar";
vm.loadAgent(agent);
// agent is started, get the connector address
connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
}
vm.detach();
JMXServiceURL url = new JMXServiceURL(connectorAddress);
this.jmxConnector = JMXConnectorFactory.connect(url);
}
}
This works fine so far but the problem is that I have now a dependency to the tools.jar
from the JDK.
My question is now can I somehow check during runtime if the tools.jar
is available in the JAVA_HOME
path and load it when it is? Because if it isn't available I just want to do the normal monitoring with Sigar, but if it is available I want to use JMX for monitoring Java applications.
My project is a maven project and I'm using the maven-shade-plugin
to create a executable jar with all dependencies in it.
Currently I'm using a dirty hack I found in the internet which uses reflection to add the tools.jar
dynamically to the system classpath if it exists. But I'm wondering if it is possible to do it differently as well?
Thanks in advance for your support.