Another piece of the tool puzzle.
By user12820862 on Jan 04, 2006
MemViewer.java is a simple "one page" example
to demonstrate how
a tool might use this method. MemViewer takes one argument to identify the target
application and for this you use the process-id (or pid). MemViewer attempts to
attach to the specified application and looks for the agent property named
"com.sun.management.jmxremote.localConnectorAddress". If this property is set then it
is the address of the local JMX connector server. If the property is not set then
it means a local JMX agent is not running so MemViewer starts the management
agent by loading a java agent named "management-agent.jar" into the target
application. Once started, it re-obtains the agent properties to get the value of the
Once MemViewer has the address of the connector server then it connects and
prints information about each of the memory pools. Here is an example where
MemViewer is used to print information about the memory used by a
Java Web Start application.
C:\\> jps -l
C:\\> java -classpath .;%JDK_HOME%\\lib\\tools.jar MemViewer 2560
Pool Used Committed Max
Perm Gen [shared-ro] 5279360 8388608 8388608
Code Cache 4901696 4980736 33554432
Eden Space 313968 1638400 4194304
Perm Gen [shared-rw] 7021848 12582912 12582912
Tenured Gen 14466928 23662592 61997056
Perm Gen 10631352 12582912 67108864
Survivor Space 196608 196608 458752
If you examine MemViewer then you will see that the code is relatively simple. VirtualMachine.attach is used to attach to the target Java virtual machine. Once attached the getAgentProperties method is used to read the agent properties. If the management agent is not running then it constructs the name of the management agent and then uses the loadAgent method to load it into the target. The Attach API is a simple tool API for bootstraping agents into a running application and ships in the JDK in tools.jar. This means that tools.jar must be on the classpath when compiling or running. The JAR file "management-agent.jar" is the java agent with the Agent-Class attribute in the main manifest to specify the class name of the agent. The agent property com.sun.management.jmxremote.localConnectorAddress is set by the agent when the local JMX connector has started. This property will be documented along with the other properties on the Monitoring and Management with JMX page.
Finally, in the example output you will see that I used jps utility to get a list of the Java virtual machines that I was running. An alternative approach would have been to use the VirtualMachine.list method and prompt the user to select from a list.