Tuesday, September 4, 2007

Threadlocal in Struts

Recently, I ran into a situation where I had to access ActionMapping while customizing Displaytag (outside of Action class) without changing any method signature to pass mapping. You can also use following technique to access request, response, session etc in any layer of the application.

After doing some search on the net I found an old friend (ThreadLocal).
I created a new calls called ThreadUtil as follows.

import java.util.HashMap;
import java.util.Map;

public class ThreadUtil {
private static ThreadLocal threadData = new ThreadLocal() {
protected synchronized Object initialValue() {
return new HashMap();
}
};
public static Object get(String key) {
return ((Map)ThreadUtil .get()).get(key);
}
public static void set(String key, Object val) {
((Map)ThreadUtil .get()).put(key,val);
}
}

After I created above class, I put my mapping as follows

ThreadUtil.set("mapping", mapping);

And retrieve it whereever you need as follows

ActionMapping mapping = (ActionMapping) ThreadUtil.get("mapping");

Though it is nothing new, I found it be very useful in my situation.

No comments: