在最近的工作中,无意中使用一个SimpleDateFormat把日期时间字符串转换为Date对象,发现存在时间很异常的情况,比如出现时间年份明显不对的情况。

后来在网上查看发现,原来是SimpleDateFormat不是线程安全导致的。后来改写了DateUtil,利用ThreadLocal达到线程安全效果。

ThreadLocal对象一个新线程里第一次被调用时,会调用initialValue方法,后续此线程就会用这个方法返回的对象进行处理,相当于每个线程有一个独立的SimpleDateFormat对象,达到了线程安全的效果。

 1 class DateUtil{
 2     private static ThreadLocal<SimpleDateFormat> threadLocal = new ThreadLocal<SimpleDateFormat>(){
 3         protected SimpleDateFormat initialValue() {
 4             return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 5         }
 6     };
 7     public static  Date parse(String strtime){
 8         try{
 9             return threadLocal.get().parse(strtime);
10         } catch( ParseException e){
11             e.printStackTrace();
12         }
13         return null;
14     }
15 
16     public static String format(Date date){
17         try{
18             return threadLocal.get().format(date);
19         } catch( Exception e){
20             e.printStackTrace();
21         }
22         return null;
23     }
24 
25 
26 }

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-08-15
  • 2021-04-22
  • 2021-06-20
  • 2022-12-23
  • 2022-02-07
  • 2021-08-12
猜你喜欢
  • 2022-12-23
  • 2021-05-28
  • 2022-12-23
  • 2021-07-27
  • 2021-05-16
  • 2022-12-23
  • 2021-09-19
相关资源
相似解决方案