最常见的 ThreadLocal 使用场景为 用来解决 数据库连接、Session 管理等。

private static final ThreadLocal threadSession = new ThreadLocal(); 
public static Session getSession() throws InfrastructureException { 
 Session s = (Session) threadSession.get(); 
 try { 
 if (s == null) { 
 s = getSessionFactory().openSession(); 
 threadSession.set(s); 
 } 
 } catch (HibernateException ex) { 
 throw new InfrastructureException(ex); 
 } 
 return s; 
}