`
aty
  • 浏览: 35467 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

JDK的ThreadLocal理解(三)优雅的使用ThreadLoca

阅读更多

ThreadLocal的使用可以参考struts2的ActionContext,个人觉得这种使用方式是比较优雅的:

1、ThreadLocal是业务无关的对象,对于开发代码来说,越少使用越好。

     这样能够尽可能的减少技术细节分散开发者对业务逻辑的关注

 

public class ActionContext implements Serializable 
{
    static ThreadLocal<ActionContext> actionContext = new  ThreadLocal<ActionContext>();

   /**
     * Sets the action context for the current thread.
     *
     * @param context the action context.
     */
    public static void setContext(ActionContext context) {
        actionContext.set(context);
    }

    /**
     * Returns the ActionContext specific to the current thread.
     *
     * @return the ActionContext for the current thread, is never <tt>null</tt>.
     */
    public static ActionContext getContext() {
        return actionContext.get();
    }
}

 经过这种封装后,整个ActionContext类,只有3个地方会涉及ThreadLocal的使用:变量定义、set、get。这3处使用都很简单,不容易出错

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics