java的SimpleDateFormat線程不安全出問題了,虛竹教你多種解決方案(JAVA 小虛竹)

      網友投稿 842 2025-04-01

      場景


      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 threadLocal = new ThreadLocal(){ @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 實例,使用默認地區
      * 支持緩存 * * @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 CACHE = new FormatCache(){ @Override protected FastDateFormat createInstance(final String pattern, final TimeZone timeZone, final Locale locale) { return new FastDateFormat(pattern, timeZone, locale); } }; // abstract class FormatCache { ... private final ConcurrentMap cInstanceCache = new ConcurrentHashMap<>(7); private static final ConcurrentMap 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); }

      java的SimpleDateFormat線程不安全出問題了,虛竹教你多種解決方案(JAVA 小虛竹)

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

      結論

      這個是阿里巴巴 java開發手冊中的規定:

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

      2、加鎖:synchronized鎖和Lock鎖

      3、使用ThreadLocal方式

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

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

      Java JDK

      版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。

      版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。

      上一篇:如何在Excel中復制隱藏的工作表?
      下一篇:wps中頁眉頁腳怎么刪除
      相關文章
      久久精品国产亚洲AV久| 波多野结衣亚洲一级| 亚洲日韩国产一区二区三区在线 | 亚洲国产欧美国产综合一区| 亚洲国产精品一区二区久| 亚洲人成在线电影| 久久伊人久久亚洲综合| 亚洲国产精品国自产电影| 亚洲AV无码码潮喷在线观看| 久久精品国产亚洲沈樵| 久久精品国产亚洲沈樵| 亚洲AV无码欧洲AV无码网站| 久久亚洲私人国产精品| 久久精品国产亚洲AV高清热| 亚洲色图古典武侠| 亚洲成a人片在线看| 亚洲熟伦熟女专区hd高清| 亚洲日韩看片无码电影| 亚洲精品人成网线在线播放va| 亚洲欧美国产国产一区二区三区 | 亚洲AV成人一区二区三区在线看| 亚洲a级成人片在线观看| 亚洲国产成人精品激情| 亚洲人成色4444在线观看| 国产精品亚洲专区无码牛牛| 国产亚洲精彩视频| 亚洲精品国产V片在线观看| 国产亚洲精品成人AA片新蒲金| 亚洲午夜未满十八勿入网站2| 亚洲精品国产精品乱码不卡√| 无码乱人伦一区二区亚洲一| 亚洲视频免费在线观看| 亚洲噜噜噜噜噜影院在线播放| 国产日本亚洲一区二区三区| 久久亚洲欧美国产精品| 久久精品国产亚洲精品| 亚洲av之男人的天堂网站| 亚洲色图校园春色| 亚洲欧洲专线一区| 亚洲综合国产精品第一页| 亚洲AV无码专区国产乱码4SE|