Java serviceability, observability tools such as jstack, jmap, jstat are run asynchronously. i.e., these tools can be "attached" to running Java program at any time (without requiring any VM event). But sometimes, you may want to run these tools on specific "event(s)". For example, you can use -XX:OnError flag to run any of these tools at the time of fatal error exit. For example, you can create heapdump on exit using jmap -F -dump command. What about other events such as gc begin/end, class load/unload, thread start/stop etc?
Mustang (Java SE 6) supports many built-in probes for DTrace. These may be used to dynamically trace JVM and your Java programs. DTrace supports system action that can be used to run arbitrary program from D-script. If you use system action along with JVM built-in probes, then you can run any of the Java serviceability tools such as jstack, jmap based on specific "event(s)". For example, you can write a D-script that triggers java heapdump after 100'th GC event occurs.
Sample D-script: test.d
int cnt;
BEGIN {
cnt = 0; /* initialize count */
}
hotspot1274:::gc_begin
{
cnt++;
}
hotspot1274:::gc-begin
/ cnt == 100 /
{
/* create java heap dump */
system("jmap -dump:format=b,file=heap.bin 1274");
}
where 1274 is pid of your java process. Heap dump is created in "heap.bin" file after 100'th GC event. More complex "events" are possible with different DTrace probe and predicate
combinations. Note that the system action is a destructive DTrace action -- this means you have to run DTrace with -w option to enable it. I ran the above script with the following command line:
/usr/sbin/dtrace -s test.d -w
More examples of running Java Serviceability tools on "events":