zoukankan      html  css  js  c++  java
  • 利用ThreadLocal解决SimplaDateFormat线程不安全的问题

    在最近的工作中,无意中使用一个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 }
  • 相关阅读:
    Python 元类
    Rsync 基础配置
    linux shell find
    找最大的目录
    云主机的上下行带宽
    关于c3p0 ResourcePoolException: Attempted to use a closed or broken resource pool
    recover_file
    MegaCli 监控raid状态
    influxdb
    在Ubuntu 16.04如何安装Java使用apt-get的
  • 原文地址:https://www.cnblogs.com/shuzl/p/5338302.html
Copyright © 2011-2022 走看看