使用DateTimeFormatter替换线程不安全的SimpleDateFormat

原文:https://blog.csdn.net/baofeidyz/article/details/81307478

如何让SimpleDateFormat保持安全运行?

方案一 每次都去new
这种方案最简单,但是会导致开销比较大,不推荐

方案二 使用ThreadLocal保障每个线程都有一个SimpleDateFormat
这个方法是我在这里看到的:https://www.jianshu.com/p/d9977a048dab
我摘一下主要内容:
---------------------
作者:暴沸
来源:CSDN
原文:https://blog.csdn.net/baofeidyz/article/details/81307478
版权声明:本文为博主原创文章,转载请附上博文链接!

public class TestSimpleDateFormat2 {
    // (1)创建threadlocal实例
    static ThreadLocal<DateFormat> safeSdf = new ThreadLocal<DateFormat>(){
        @Override 
        protected SimpleDateFormat initialValue(){
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };

    public static void main(String[] args) {
        // (2)创建多个线程,并启动
        for (int i = 0; i < 10; ++i) {
            Thread thread = new Thread(new Runnable() {
                public void run() {
                    try {// (3)使用单例日期实例解析文本
                            System.out.println(safeSdf.get().parse("2017-12-13 15:17:27"));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            });
            thread.start();// (4)启动线程
        }
    }
} 

方案三 使用第三方包
这个我有尝试cn.hutool和common-lang3提供的FastDateFormat
最后的结果其实并不满意,因为这两个包都没能帮助我检查非正常时间,比如2018-07-32这种日期也被认为是正确的时期格式了

方案四 使用JDK8提供的DateTimeFormatter
这个方案就比较完美了,该有的都有了。

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
 

原文地址:https://www.cnblogs.com/shihaiming/p/11082172.html