The Thread Tracker Pattern

Basically, this pattern helps to analyze problems and errors by clearly defining the name for the current thread because sometimes we are in multithreaded environment and it is very difficult to know who caused the error.

Adam Bien posted his Thread Tracker Pattern. This page is an adoption of his work. Changing the name of the current thread is not explicitly allowed by the JEE specification, but it is also not forbidden. Changing the name of the current thread is an example of either a ServletFilter, an EJB Interceptor or an AOP(AspectJ) aspect. Using one of those technologies can save a lot of time.

 

import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import java.lang.reflect.Method;

@Interceptor
@ThreadTracking
public class ThreadTracker {

@AroundInvoke
public Object handleInvocation(InvocationContext aContext) throws Exception {
Method theMethod = aContext.getMethod();
String theCurrentThreadName = Thread.currentThread().getName();
try {
Thread.currentThread().setName(theMethod.getDeclaringClass().getSimpleName() + “.” + theMethod.getName());
return aContext.proceed();
} finally {
Thread.currentThread().setName(theCurrentThreadName);
}
}
}

 

 

 

Leave a comment