解决SimpleDateFormat线程安全问题

 1 package com.tanlu.user.util;
 2 
 3 import java.text.DateFormat;
 4 import java.text.ParseException;
 5 import java.text.SimpleDateFormat;
 6 import java.util.Date;
 7 
 8 /**
 9  * 考虑到SimpleDateFormat为线程不安全对象,故应用ThreadLocal来解决,
10  * 使SimpleDateFormat从独享变量变成单个线程变量
11  */
12 public class ThreadLocalDateUtil {
13 
14     //写法1:
15     /*private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>() {
16         @Override
17         protected DateFormat initialValue() {
18             return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
19         }
20     };
21 
22     public static Date parse(String dateStr) throws ParseException {
23         return threadLocal.get().parse(dateStr);
24     }
25 
26     public static String format(Date date) {
27         return threadLocal.get().format(date);
28     }*/
29 
30 
31     //写法2:
32     private static final String date_format = "yyyy-MM-dd HH:mm:ss";
33     private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>();
34 
35     public static DateFormat getDateFormat() {
36         DateFormat df = threadLocal.get();
37         if(df == null){
38             df = new SimpleDateFormat(date_format);
39             threadLocal.set(df);
40         }
41         return df;
42     }
43 
44     public static String formatDate(Date date) throws ParseException {
45         return getDateFormat().format(date);
46     }
47 
48     public static Date parse(String strDate) throws ParseException {
49         return getDateFormat().parse(strDate);
50     }
51 
52 
53 }

 

posted @ 2019-04-12 13:35  小柴胡颗粒  阅读(555)  评论(0编辑  收藏  举报