SimpleDateFormat線程不安全了?這里有5種解決方案


摘要:我們知道SimpleDateFormat是線程不安全,本文會介紹多種解決方案來保證線程安全。

本文分享自華為雲社區《java的SimpleDateFormat線程不安全出問題了,虛竹教你多種解決方案》,作者:小虛竹 。

場景

在java8以前,要格式化日期時間,就需要用到SimpleDateFormat。

但我們知道SimpleDateFormat是線程不安全的,處理時要特別小心,要加鎖或者不能定義為static,要在方法內new出對象,再進行格式化。很麻煩,而且重復地new出對象,也加大了內存開銷。

SimpleDateFormat線程為什么是線程不安全的呢?

來看看SimpleDateFormat的源碼,先看format方法:

// Called from Format after creating a FieldDelegate
    private StringBuffer format(Date date, StringBuffer toAppendTo,
                                FieldDelegate delegate) {
        // Convert input date to time field list
        calendar.setTime(date);
        ...
    }

問題就出在成員變量calendar,如果在使用SimpleDateFormat時,用static定義,那SimpleDateFormat變成了共享變量。那SimpleDateFormat中的calendar就可以被多個線程訪問到。

SimpleDateFormat的parse方法也是線程不安全的:

 public Date parse(String text, ParsePosition pos)
    {
     ...
         Date parsedDate;
        try {
            parsedDate = calb.establish(calendar).getTime();
            // If the year value is ambiguous,
            // then the two-digit year == the default start year
            if (ambiguousYear[0]) {
                if (parsedDate.before(defaultCenturyStart)) {
                    parsedDate = calb.addYear(100).establish(calendar).getTime();
                }
            }
        }
        // An IllegalArgumentException will be thrown by Calendar.getTime()
        // if any fields are out of range, e.g., MONTH == 17.
        catch (IllegalArgumentException e) {
            pos.errorIndex = start;
            pos.index = oldStart;
            return null;
        }

        return parsedDate;  
 }

由源碼可知,最后是調用**parsedDate = calb.establish(calendar).getTime();**獲取返回值。方法的參數是calendar,calendar可以被多個線程訪問到,存在線程不安全問題。

我們再來看看**calb.establish(calendar)**的源碼

calb.establish(calendar)方法先后調用了cal.clear()和cal.set(),先清理值,再設值。但是這兩個操作並不是原子性的,也沒有線程安全機制來保證,導致多線程並發時,可能會引起cal的值出現問題了。

驗證SimpleDateFormat線程不安全

public class SimpleDateFormatDemoTest {

    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) {
            //1、創建線程池
        ExecutorService pool = Executors.newFixedThreadPool(5);
        //2、為線程池分配任務
        ThreadPoolTest threadPoolTest = new ThreadPoolTest();
        for (int i = 0; i < 10; i++) {
            pool.submit(threadPoolTest);
        }
        //3、關閉線程池
        pool.shutdown();
    }
    static class  ThreadPoolTest implements Runnable{

        @Override
        public void run() {
                String dateString = simpleDateFormat.format(new Date());
                try {
                    Date parseDate = simpleDateFormat.parse(dateString);
                    String dateString2 = simpleDateFormat.format(parseDate);
                    System.out.println(Thread.currentThread().getName()+" 線程是否安全: "+dateString.equals(dateString2));
                } catch (Exception e) {
                    System.out.println(Thread.currentThread().getName()+" 格式化失敗 ");
                }
        }
    }
}

 

出現了兩次false,說明線程是不安全的。而且還拋異常,這個就嚴重了。

解決方案

解決方案1:不要定義為static變量,使用局部變量

就是要使用SimpleDateFormat對象進行format或parse時,再定義為局部變量。就能保證線程安全。

public class SimpleDateFormatDemoTest1 {

    public static void main(String[] args) {
            //1、創建線程池
        ExecutorService pool = Executors.newFixedThreadPool(5);
        //2、為線程池分配任務
        ThreadPoolTest threadPoolTest = new ThreadPoolTest();
        for (int i = 0; i < 10; i++) {
            pool.submit(threadPoolTest);
        }
        //3、關閉線程池
        pool.shutdown();
    }
    static class  ThreadPoolTest implements Runnable{

        @Override
        public void run() {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateString = simpleDateFormat.format(new Date());
            try {
                Date parseDate = simpleDateFormat.parse(dateString);
                String dateString2 = simpleDateFormat.format(parseDate);
                System.out.println(Thread.currentThread().getName()+" 線程是否安全: "+dateString.equals(dateString2));
            } catch (Exception e) {
                System.out.println(Thread.currentThread().getName()+" 格式化失敗 ");
            }
        }
    }
}

 

由圖可知,已經保證了線程安全,但這種方案不建議在高並發場景下使用,因為會創建大量的SimpleDateFormat對象,影響性能。

解決方案2:加鎖:synchronized鎖和Lock鎖

加synchronized鎖

SimpleDateFormat對象還是定義為全局變量,然后需要調用SimpleDateFormat進行格式化時間時,再用synchronized保證線程安全。

public class SimpleDateFormatDemoTest2 {

    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) {
            //1、創建線程池
        ExecutorService pool = Executors.newFixedThreadPool(5);
        //2、為線程池分配任務
        ThreadPoolTest threadPoolTest = new ThreadPoolTest();
        for (int i = 0; i < 10; i++) {
            pool.submit(threadPoolTest);
        }
        //3、關閉線程池
        pool.shutdown();
    }

    static class  ThreadPoolTest implements Runnable{

        @Override
        public void run() {
            try {
                synchronized (simpleDateFormat){
                    String dateString = simpleDateFormat.format(new Date());
                    Date parseDate = simpleDateFormat.parse(dateString);
                    String dateString2 = simpleDateFormat.format(parseDate);
                    System.out.println(Thread.currentThread().getName()+" 線程是否安全: "+dateString.equals(dateString2));
                }
            } catch (Exception e) {
                System.out.println(Thread.currentThread().getName()+" 格式化失敗 ");
            }
        }
    }
}

 

如圖所示,線程是安全的。定義了全局變量SimpleDateFormat,減少了創建大量SimpleDateFormat對象的損耗。但是使用synchronized鎖,
同一時刻只有一個線程能執行鎖住的代碼塊,在高並發的情況下會影響性能。但這種方案不建議在高並發場景下使用

加Lock鎖

加Lock鎖和synchronized鎖原理是一樣的,都是使用鎖機制保證線程的安全。

public class SimpleDateFormatDemoTest3 {

    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static Lock lock = new ReentrantLock();
    public static void main(String[] args) {
            //1、創建線程池
        ExecutorService pool = Executors.newFixedThreadPool(5);
        //2、為線程池分配任務
        ThreadPoolTest threadPoolTest = new ThreadPoolTest();
        for (int i = 0; i < 10; i++) {
            pool.submit(threadPoolTest);
        }
        //3、關閉線程池
        pool.shutdown();
    }

    static class  ThreadPoolTest implements Runnable{

        @Override
        public void run() {
            try {
                lock.lock();
                    String dateString = simpleDateFormat.format(new Date());
                    Date parseDate = simpleDateFormat.parse(dateString);
                    String dateString2 = simpleDateFormat.format(parseDate);
                    System.out.println(Thread.currentThread().getName()+" 線程是否安全: "+dateString.equals(dateString2));
            } catch (Exception e) {
                System.out.println(Thread.currentThread().getName()+" 格式化失敗 ");
            }finally {
                lock.unlock();
            }
        }
    }
}

 

由結果可知,加Lock鎖也能保證線程安全。要注意的是,最后一定要釋放鎖,代碼里在finally里增加了lock.unlock();,保證釋放鎖。

在高並發的情況下會影響性能。這種方案不建議在高並發場景下使用

解決方案3:使用ThreadLocal方式

使用ThreadLocal保證每一個線程有SimpleDateFormat對象副本。這樣就能保證線程的安全。

public class SimpleDateFormatDemoTest4 {

    private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>(){
        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };
    public static void main(String[] args) {
            //1、創建線程池
        ExecutorService pool = Executors.newFixedThreadPool(5);
        //2、為線程池分配任務
        ThreadPoolTest threadPoolTest = new ThreadPoolTest();
        for (int i = 0; i < 10; i++) {
            pool.submit(threadPoolTest);
        }
        //3、關閉線程池
        pool.shutdown();
    }

    static class  ThreadPoolTest implements Runnable{

        @Override
        public void run() {
            try {
                    String dateString = threadLocal.get().format(new Date());
                    Date parseDate = threadLocal.get().parse(dateString);
                    String dateString2 = threadLocal.get().format(parseDate);
                    System.out.println(Thread.currentThread().getName()+" 線程是否安全: "+dateString.equals(dateString2));
            } catch (Exception e) {
                System.out.println(Thread.currentThread().getName()+" 格式化失敗 ");
            }finally {
                //避免內存泄漏,使用完threadLocal后要調用remove方法清除數據
                threadLocal.remove();
            }
        }
    }
}

 

使用ThreadLocal能保證線程安全,且效率也是挺高的。適合高並發場景使用。

解決方案4:使用DateTimeFormatter代替SimpleDateFormat

使用DateTimeFormatter代替SimpleDateFormat(DateTimeFormatter是線程安全的,java 8+支持)
DateTimeFormatter介紹 傳送門:萬字博文教你搞懂java源碼的日期和時間相關用法

public class DateTimeFormatterDemoTest5 {
    private static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) {
        //1、創建線程池
        ExecutorService pool = Executors.newFixedThreadPool(5);
        //2、為線程池分配任務
        ThreadPoolTest threadPoolTest = new ThreadPoolTest();
        for (int i = 0; i < 10; i++) {
            pool.submit(threadPoolTest);
        }
        //3、關閉線程池
        pool.shutdown();
    }
    static class  ThreadPoolTest implements Runnable{

        @Override
        public void run() {
            try {
                String dateString = dateTimeFormatter.format(LocalDateTime.now());
                TemporalAccessor temporalAccessor = dateTimeFormatter.parse(dateString);
                String dateString2 = dateTimeFormatter.format(temporalAccessor);
                System.out.println(Thread.currentThread().getName()+" 線程是否安全: "+dateString.equals(dateString2));
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(Thread.currentThread().getName()+" 格式化失敗 ");
            }
        }
    }
}

 

使用DateTimeFormatter能保證線程安全,且效率也是挺高的。適合高並發場景使用。

解決方案5:使用FastDateFormat 替換SimpleDateFormat

使用FastDateFormat 替換SimpleDateFormat(FastDateFormat 是線程安全的,Apache Commons Lang包支持,不受限於java版本)

public class FastDateFormatDemo6 {
    private static FastDateFormat fastDateFormat = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) {
        //1、創建線程池
        ExecutorService pool = Executors.newFixedThreadPool(5);
        //2、為線程池分配任務
        ThreadPoolTest threadPoolTest = new ThreadPoolTest();
        for (int i = 0; i < 10; i++) {
            pool.submit(threadPoolTest);
        }
        //3、關閉線程池
        pool.shutdown();
    }
    static class  ThreadPoolTest implements Runnable{

        @Override
        public void run() {
            try {
                String dateString = fastDateFormat.format(new Date());
                Date parseDate =  fastDateFormat.parse(dateString);
                String dateString2 = fastDateFormat.format(parseDate);
                System.out.println(Thread.currentThread().getName()+" 線程是否安全: "+dateString.equals(dateString2));
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(Thread.currentThread().getName()+" 格式化失敗 ");
            }
        }
    }
}

使用FastDateFormat能保證線程安全,且效率也是挺高的。適合高並發場景使用。

FastDateFormat源碼分析

Apache Commons Lang 3.5
//FastDateFormat
@Override
public String format(final Date date) {
   return printer.format(date);
}

    @Override
    public String format(final Date date) {
        final Calendar c = Calendar.getInstance(timeZone, locale);
        c.setTime(date);
        return applyRulesToString(c);
    }

源碼中 Calender 是在 format 方法里創建的,肯定不會出現 setTime 的線程安全問題。這樣線程安全疑惑解決了。那還有性能問題要考慮?

我們來看下FastDateFormat是怎么獲取的

FastDateFormat.getInstance();
FastDateFormat.getInstance(CHINESE_DATE_TIME_PATTERN);

看下對應的源碼

/**
 * 獲得 FastDateFormat實例,使用默認格式和地區
 *
 * @return FastDateFormat
 */
public static FastDateFormat getInstance() {
   return CACHE.getInstance();
}

/**
 * 獲得 FastDateFormat 實例,使用默認地區<br>
 * 支持緩存
 *
 * @param pattern 使用{@link java.text.SimpleDateFormat} 相同的日期格式
 * @return FastDateFormat
 * @throws IllegalArgumentException 日期格式問題
 */
public static FastDateFormat getInstance(final String pattern) {
   return CACHE.getInstance(pattern, null, null);
}

這里有用到一個CACHE,看來用了緩存,往下看

private static final FormatCache<FastDateFormat> CACHE = new FormatCache<FastDateFormat>(){
   @Override
   protected FastDateFormat createInstance(final String pattern, final TimeZone timeZone, final Locale locale) {
      return new FastDateFormat(pattern, timeZone, locale);
   }
};

//
abstract class FormatCache<F extends Format> {
    ...
    private final ConcurrentMap<Tuple, F> cInstanceCache = new ConcurrentHashMap<>(7);

    private static final ConcurrentMap<Tuple, String> C_DATE_TIME_INSTANCE_CACHE = new ConcurrentHashMap<>(7);
    ...
}

 

在getInstance 方法中加了ConcurrentMap 做緩存,提高了性能。且我們知道ConcurrentMap 也是線程安全的。

實踐

/**
 * 年月格式 {@link FastDateFormat}:yyyy-MM
 */
public static final FastDateFormat NORM_MONTH_FORMAT = FastDateFormat.getInstance(NORM_MONTH_PATTERN);

 

//FastDateFormat
public static FastDateFormat getInstance(final String pattern) {
   return CACHE.getInstance(pattern, null, null);
}

 

如圖可證,是使用了ConcurrentMap 做緩存。且key值是格式,時區和locale(語境)三者都相同為相同的key。

結論

1、不要定義為static變量,使用局部變量

2、加鎖:synchronized鎖和Lock鎖

3、使用ThreadLocal方式

4、使用DateTimeFormatter代替SimpleDateFormat(DateTimeFormatter是線程安全的,java 8+支持)

5、使用FastDateFormat 替換SimpleDateFormat(FastDateFormat 是線程安全的,Apache Commons Lang包支持,java8之前推薦此用法)

 

點擊關注,第一時間了解華為雲新鮮技術~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM