关于ThreadLocal模式的体会
写这篇帖子的目的不是为了来剖析ThreadLocal,因为坛子里有许多高手已经深入浅出的把ThreadLocal讲解的很清楚了。
特别是lujh99的正确理解ThreadLocal这篇帖子,通过JDK源代码把ThreadLocal讲得非常深入浅出,让我深受启发。我写这篇帖子的目的只是为再此作一个补充,想以另外一种通俗易懂的表达方式把自己对ThreadLocal理解写出来。
?
?
doFilter(){设置threadlocal变量;filterChain.doFilter();清除threadlocal变量;}public static synchronized String format(Date date) {return formator.format(date);}
public static String format(Date date) {SimpleDateFormat formator = new SimpleDateFormat("yyMMddHHmmss");return formator.format(date);}
public class Foo {static ThreadLocal local = new ThreadLocal();public static String format(Date date) {SimpleDateFormat formator = (SimpleDateFormat)local.get();if (formator == null) {formator = new SimpleDateFormat("yyMMddHHmmss");local.set(formator);}return formator.format(date);}}
public static synchronized String format(Date date) {return formator.format(date);}
public static String format(Date date) {SimpleDateFormat formator = new SimpleDateFormat("yyMMddHHmmss");return formator.format(date);}
public class Foo {static ThreadLocal local = new ThreadLocal();public static String format(Date date) {SimpleDateFormat formator = (SimpleDateFormat)local.get();if (formator == null) {formator = new SimpleDateFormat("yyMMddHHmmss");local.set(formator);}return formator.format(date);}}
doFilter(){设置threadlocal变量;try {filterChain.doFilter();}finally {清除threadlocal变量;}}private static synchronized int nextHashCode() { int h = nextHashCode; nextHashCode = h + HASH_INCREMENT; return h; }