BTrace can save your day

Today I had a problem with a scheduled job in a application deployed on GlassFish. The execution time was too long but I could not find out how long. The system was deployed in a test environment and to do changes in the code to log out execution time was possible, but the roundtrip time to do the changes and rebuild and deploy is always a little bit to long.

So I saw the chance to using some BTrace scripts instead. BTrace is a great tool for instrumenting your classes in runtime without any restart of your application. It just connects to the JVM process and installs the BTrace javaagent in runtime and compiles and connects to the javaagent and instruments the classes specified in your BTrace script.

So I downloaded BTrace for here. Installed it on the test server.

Created the java class

import static com.sun.btrace.BTraceUtils.*;
import com.sun.btrace.annotations.*;

@BTrace public class MethodTimer {
   // store entry time in thread local
   @TLS private static long startTime;

   public static void onMethodEntry() {
       startTime = timeMillis();

   public static void onMethodReturn() {
       println(strcat("Time taken (msec) ", str(timeMillis() - startTime)));

Then I just issued the command:

btrace <pid>

Then the my little BTrace script prints the execution time for every invocation of Without any recompilation and redeployment of the application.

2 thoughts on “BTrace can save your day”

  1. In case you are using BTrace 1.2 you can use the builtin @Duration annotation to gather the time spent in a particular method. Also you should consider using the builtin Profiler class to collect the timing data – it is highly optimized and also removes rather high performance penalty of accessing thread local variables.

Comments are closed.