JavaChap Blog Java and Technology musings for the masses

22Dec/080

Debugging in Java

The Java Debugger

The Java Debugger (jdb) helps you find and fix bugs in Java language programs both locally and on the server. A VM that is to be debugged with jdb must be started with the following options:

-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8000

-Xdebug will instruct the VM to enable debugging support.

-Xrunjdwp <options> will load the JPDA reference implementation of JDWP.

Xrunjdwp Options

  • transport=dt_socket instructs JVM that the debugger connections will be made through a socket
  • address=8000 instructs JVM that the socket will be opened on port 8000
  • suspend=n If configured as 'y' the JVM starts in suspended mode and stays suspended until a debugger attaches to it. This is helpful if you want to start debugging as soon as the JVM starts.
  • server=y If "y", listen for a debugger application to attach; otherwise, attach to the debugger application at the specified address. 

for more options visit http://java.sun.com/j2se/1.4.2/docs/guide/jpda/conninv.html#Xrunjdwp

Remote Debugging in Tomcat

To enable debugging in tomcat set an environment variable called JAVA_OPTS, You can set this catalina.bat

>set JAVA_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n

In Linux,  Add the following Configuration in /etc/tomcat5/tomcat5.conf

JAVA_OPTS="$JAVA_OPTS -Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"

View Heap Dump

Hit Ctrl + Break to dump a list of threads and all their held locks to stdout. If your app is stuck, you can figure out what it is doing. If it is deadlocked, sometimes the JVM can even tell you exactly which threads are involved. If you are running the java application as a service then you will need a tool to send a SIGINT signal to the JVM. One such tool is SendSignal

Record heap dump on OutOfMemory

The most common problem that we run into is OutOfMemoryError, this happens when there is memory leakage. By specifying some options we can instruct JVM to take the heap dump when the JVM runs out of memory. The JVM must be configured with following options to record the heap dump

-Xrunhprof:heap=dump,format=b -XX:+HeapDumpOnOutOfMemoryError

If you don't want big dump files in the application working directory then the HeapDumpPath option can be used to specify an alternative location, for  example -XX:HeapDumpPath=/disk2/dumps will cause the heap dump to be generated in the /disk2/dumps directory.

Note: To list all available options, use java -Xrunhprof:help

Reference