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);
}
}
}

 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s