ThreadLocal을 이용하여 호출되는 비즈니스 메소드들의 순서를 추적할 때 사용할 수 있는 예제 코드입니다. 좀 중요한 것을 만들고 있는데 그것의 뼈대 코드라고 할 수 있습니다.
아주 단순한 예제라 그리 어렵지 않을 듯 합니다. ThreadLocal이란 것에 대해서는 구글링을 해보시면 많이 나올 겁니다. 이것과 Java instrumentation을 이용하면 bytecode레벨을 조작하여 성능에 별 영향없이 profiling tool을 만들 수 있습니다.
CapturedTransaction.java
package org.jboss.jam.plugin.profiler;
import java.util.Stack;
public class CapturedTransaction {
protected long startTime = 0L;
protected String methodName;
protected CapturedTransaction(String methodName) {
this.startTime = System.currentTimeMillis();
this.methodName = methodName;
}
protected static ThreadLocal<Stack<CapturedTransaction>> threadLocal = new ThreadLocal<Stack<CapturedTransaction>>() {
protected synchronized Stack<CapturedTransaction> initialValue() {
return new Stack<CapturedTransaction>();
}
};
/**
* Starts a CapturedTransaction snapshot.
* Elapsed time will be captured in milliseconds
*/
public static void start(String methodName) {
threadLocal.get().push(new CapturedTransaction(methodName));
}
public static void end() {
CapturedTransaction snapshot = threadLocal.get().pop();
long elapsedTime = System.currentTimeMillis() - snapshot.startTime;
System.out.println(snapshot.methodName + " >>> " + elapsedTime);
}
}
A.java
package org.jboss.jam.plugin.profiler.test;
import org.jboss.jam.plugin.profiler.CapturedTransaction;
public class A {
public static void main(String [] args) {
CapturedTransaction.start("A.main");
B b = new B();
b.start();
System.out.println("A : " + Thread.currentThread().getName());
CapturedTransaction.end();
}
}
B.java
package org.jboss.jam.plugin.profiler.test;
import org.jboss.jam.plugin.profiler.CapturedTransaction;
public class B extends Thread{
public void run() {
CapturedTransaction.start("B.business");
C c = new C();
System.out.println("Hello B");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c.business();
System.out.println("B : " + Thread.currentThread().getName());
CapturedTransaction.end();
}
}
package org.jboss.jam.plugin.profiler.test;
import org.jboss.jam.plugin.profiler.CapturedTransaction;
public class C {
public void business() {
CapturedTransaction.start("C.business()");
System.out.println("Hello C");
System.out.println("C : " + Thread.currentThread().getName());
CapturedTransaction.end();
}
}
크리에이티브 커먼즈 라이센스
http://www.javapattern.info/trackback/325