ITeye博客

ThreadLocal原理与应用

walklen · 2011-12-13 13:04 · java-concurrent · 编程语言 · Markdown

最近在维护一个老(很老)系统,本想重构,但是目前没这个时间,基于struts1+dao,有些还是jsp+dao的方式,用户需要在敏感的操作上加比较详细的日志,日志的功能在dao根据需求手动写入,主要的问题是原有的接口没有传入request的相关信息,比如用户信息,我想到了ThreadLocal,因为每个servlet是基于多线程,但是每个request的执行是再一个独立的线程中完成,ThreadLocal正适合了我这种需求,可以用来完成我对这个系统的业务扩展。 在比如struts2的ServletActionContext中对request的获取,还有hibernate中对sessin的管理就是基于ThreadLocal来实现。 看了下ThreadLocal的源码,相对简单,主要的思路是在每个Thread中维护一个ThreadLocalMap,调用ThreadLocal的set(T value)的时候,以当前的ThreadLocal实例为key保存到当前线程的ThreadLocalMap中。

关键源码如下: public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); } public T get() { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) { ThreadLocalMap.Entry e = map.getEntry(this); if (e != null) return (T)e.value; } return setInitialValue(); }

理解了上面的以后,使用起来就方便了。我的地体实现如在 1.在web.xml中配置系统每个请求都经过的过滤器 AppRequestFilter com.clifford.restaurant.AppRequestFilter AppRequestFilter .jsp AppRequestFilter .do

2.过滤器实现 public class AppRequestFilter implements Filter{ public void destroy() { } public void doFilter(ServletRequest arg0, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = ((HttpServletRequest)arg0); RequestThreadLocal.setRequestThreadLocal(request); filterChain.doFilter(request, response); } }

3.ThreadLocal相关实现 public class RequestThreadLocal { private static ThreadLocal requestThreadLocal = new ThreadLocal(); public static void setRequestThreadLocal(HttpServletRequest request) { requestThreadLocal.set(request); } public static User getLoginUser() { HttpServletRequest request = requestThreadLocal.get(); Session session = request==null?null:request.getSession(false); return session==null?null:(User)session.getAttribute(IConstants.USER_KEY); } public static String getRequestIp() { HttpServletRequest request = requestThreadLocal.get(); return request==null?"":request.getRemoteHost(); }

}

评论(1)

  1. #1 楼 · gbd203 · 2012-02-24 22:44

    :lol: 谢谢

评论功能维护中,当前仅展示历史评论。