Saturday, June 8, 2013

Getting started with Btrace

User Guide: https://kenai.com/projects/btrace/pages/UserGuide

Download binaries here:
https://github.com/jbachorik/btrace/releases/tag/v1.3.3

Java class under test:
BTraceTest.java:
public class BTraceTest {
    public static void main(String[] args) throws Exception {
        for (int i = 0; i < 1000000; i++) {
             Thread.sleep(1000);
             doSomething();
        }
    }

    public static void doSomething() {
        System.out.println("something");
    }

}





Btrace profiling class: Btrace1.java:
import com.sun.btrace.annotations.*;
import static com.sun.btrace.BTraceUtils.*;
import java.lang.reflect.Field;

@BTrace public class Btrace1 {
  @OnMethod(
    clazz="BTraceTest",
    method="doSomething"
  )
  public static void onDoSomething() {
      println("got it");
  }
}



compile it:
./btracec -classpath . ./Btrace1.java
run it:
./btrace -classpath . 24160 ./Btrace1.class
where 24160 is the PID of the BTraceTest java application
It works! It's great!
A slightly more advanced example using Class parameters:

public class BTraceTest {
    public static void main(String[] args) throws Exception {
        for (int i = 0; i < 1000000; i++) {
             Thread.sleep(1000);
    BTraceParam param = new BTraceParam();
    param.name = "hello " + i;
             doSomething(param);
        }
    }

    public static void doSomething(BTraceParam param) {
        System.out.println("something" + param.name);
    }

}



public class BTraceParam {
 String name;
}



import com.sun.btrace.annotations.*;
import static com.sun.btrace.BTraceUtils.*;
import com.sun.btrace.AnyType;
import java.lang.reflect.Field;

@BTrace public class Btrace1 {
  @OnMethod(
    clazz="BTraceTest",
    method="doSomething"
  )

  public static void anyDoSomething(@ProbeClassName String pcn, @ProbeMethodName String pmn, AnyType[] args) {
 println(pcn);
 println(pmn);
 printArray(args);
  }
}



this way you can print the value also of any parameter !

To print the stacktrace (very useful!) use jstack();



No comments: