Profiling application

You can profile local and remote Java applications using Java VisualVM.

For the local application is easy because it detects automatically and show them in the listing. For the remote application you need to do a little work.  

Edit Tomcat startup scripts

Edit the $TOMCAT_HOME/bin/setenv.* files ( sentenv.sh for linux and setenv.bat for Windows ).

The java.rmi.server.hostname should match the IP of the server, usually the 127.0.0.1 value by the right IP.

CATALINA_OPTS="$CATALINA_OPTS -Dcom.sun.management.jmxremote=true"
CATALINA_OPTS="$CATALINA_OPTS -Dcom.sun.management.jmxremote.port=9090"
CATALINA_OPTS="$CATALINA_OPTS -Dcom.sun.management.jmxremote.ssl=false"
CATALINA_OPTS="$CATALINA_OPTS -Dcom.sun.management.jmxremote.authenticate=false"
CATALINA_OPTS="$CATALINA_OPTS -Djava.rmi.server.hostname=127.0.0.1"

To connect to this remote Tomcat instance:

  • Go to File > Add JMX Connection... and fill the hostname and port.
  • Additionally can change the port is 9090 using the com.sun.management.jmxremote.port property.

Authentication

To enhance security, enable authentication. Edit the $TOMCAT_HOME/bin/setenv.* files ( sentenv.sh for linux and setenv.bat for Windows ).

CATALINA_OPTS="$CATALINA_OPTS -Dcom.sun.management.jmxremote.authenticate=true"
CATALINA_OPTS="$CATALINA_OPTS -Dcom.sun.management.jmxremote.password.file=$CATALINA_HOME/conf/jmxremote.password"
CATALINA_OPTS="$CATALINA_OPTS -Dcom.sun.management.jmxremote.access.file=$CATALINA_HOME/conf/jmxremote.access"

Edit the access allow file $CATALINA_HOME/conf/jmxremote.access:  

monitorRole readonly
controlRole readwrite

To show remote threads you need the readwrite permission.

Edit the password file $CATALINA_BASE/conf/jmxremote.password:  

monitorRole tomcat
controlRole tomcat

Restrict access to these files:  

$ chmod 600 $CATALINA_HOME/conf/jmxremote.access
$ chmod 600 $CATALINA_HOME/conf/jmxremote.password

Monitoring Remote JVM Over SSH

The easiest way to connect to the remote JMX is to use a SOCKS proxy.  

$ ssh user@external.server.ip -D 8888

Configure VisualVM to use this proxy. Go to Tools > Options > Network and edit Manual Proxy Settings. Configure SOCKS Proxy at localhost and port 8888.  


Now you can connect VisualVM to the remote target. Go to File > Add JMX Connection... and type the IP or hostname of the remote machine and the configured JMX port (in our sample configuration is 9090).

HPROF

Java includes HPROF, a profiler which collect application runtime information. HPROF is capable of presenting CPU usage, heap allocation statistics, and monitor contention profiles.

For example, can collect CPU usage information by sampling threads.

Edit $TOMCAT_HOME/bin/setenv.sh file (or setenv.bat if using Windows):

CATALINA_OPTS="$CATALINA_OPTS -agentlib:hprof=cpu=samples"

When Tomcat starts you can see a file called java.hprof.txt. The CPU profiling info will be dumped to this file once Tomcat process is stopped.

More information at: