java的SimpleDateFormat線程不安全的幾種解決方案
場(chǎng)景
在java8以前,要格式化日期時(shí)間,就需要用到SimpleDateFormat。
但我們知道SimpleDateFormat是線程不安全的,處理時(shí)要特別小心,要加鎖或者不能定義為static,要在方法內(nèi)new出對(duì)象,再進(jìn)行格式化。很麻煩,而且重復(fù)地new出對(duì)象,也加大了內(nèi)存開銷。
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時(shí),用static定義,那SimpleDateFormat變成了共享變量。那SimpleDateFormat中的calendar就可以被多個(gè)線程訪問到。
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; }
由源碼可知,最后是調(diào)用**parsedDate = calb.establish(calendar).getTime();**獲取返回值。方法的參數(shù)是calendar,calendar可以被多個(gè)線程訪問到,存在線程不安全問題。
我們?cè)賮砜纯?*calb.establish(calendar)**的源碼
calb.establish(calendar)方法先后調(diào)用了cal.clear()和cal.set(),先清理值,再設(shè)值。但是這兩個(gè)操作并不是原子性的,也沒有線程安全機(jī)制來保證,導(dǎo)致多線程并發(fā)時(shí),可能會(huì)引起cal的值出現(xiàn)問題了。
驗(yàn)證SimpleDateFormat線程不安全
public class SimpleDateFormatDemoTest { private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static void main(String[] args) { //1、創(chuàng)建線程池 ExecutorService pool = Executors.newFixedThreadPool(5); //2、為線程池分配任務(wù) ThreadPoolTest threadPoolTest = new ThreadPoolTest(); for (int i = 0; i < 10; i++) { pool.submit(threadPoolTest); } //3、關(guān)閉線程池 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()+" 格式化失敗 "); } } } }
出現(xiàn)了兩次false,說明線程是不安全的。而且還拋異常,這個(gè)就嚴(yán)重了。
解決方案
解決方案1:不要定義為static變量,使用局部變量
就是要使用SimpleDateFormat對(duì)象進(jìn)行format或parse時(shí),再定義為局部變量。就能保證線程安全。
public class SimpleDateFormatDemoTest1 { public static void main(String[] args) { //1、創(chuàng)建線程池 ExecutorService pool = Executors.newFixedThreadPool(5); //2、為線程池分配任務(wù) ThreadPoolTest threadPoolTest = new ThreadPoolTest(); for (int i = 0; i < 10; i++) { pool.submit(threadPoolTest); } //3、關(guān)閉線程池 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()+" 格式化失敗 "); } } } }
由圖可知,已經(jīng)保證了線程安全,但這種方案不建議在高并發(fā)場(chǎng)景下使用,因?yàn)闀?huì)創(chuàng)建大量的SimpleDateFormat對(duì)象,影響性能。
解決方案2:加鎖:synchronized鎖和Lock鎖 加synchronized鎖
SimpleDateFormat對(duì)象還是定義為全局變量,然后需要調(diào)用SimpleDateFormat進(jìn)行格式化時(shí)間時(shí),再用synchronized保證線程安全。
public class SimpleDateFormatDemoTest2 { private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static void main(String[] args) { //1、創(chuàng)建線程池 ExecutorService pool = Executors.newFixedThreadPool(5); //2、為線程池分配任務(wù) ThreadPoolTest threadPoolTest = new ThreadPoolTest(); for (int i = 0; i < 10; i++) { pool.submit(threadPoolTest); } //3、關(guān)閉線程池 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,減少了創(chuàng)建大量SimpleDateFormat對(duì)象的損耗。但是使用synchronized鎖,
同一時(shí)刻只有一個(gè)線程能執(zhí)行鎖住的代碼塊,在高并發(fā)的情況下會(huì)影響性能。但這種方案不建議在高并發(fā)場(chǎng)景下使用
加Lock鎖
加Lock鎖和synchronized鎖原理是一樣的,都是使用鎖機(jī)制保證線程的安全。
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、創(chuàng)建線程池 ExecutorService pool = Executors.newFixedThreadPool(5); //2、為線程池分配任務(wù) ThreadPoolTest threadPoolTest = new ThreadPoolTest(); for (int i = 0; i < 10; i++) { pool.submit(threadPoolTest); } //3、關(guān)閉線程池 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(); } } } }
由結(jié)果可知,加Lock鎖也能保證線程安全。要注意的是,最后一定要釋放鎖,代碼里在finally里增加了lock.unlock();,保證釋放鎖。
在高并發(fā)的情況下會(huì)影響性能。這種方案不建議在高并發(fā)場(chǎng)景下使用
解決方案3:使用ThreadLocal方式
使用ThreadLocal保證每一個(gè)線程有SimpleDateFormat對(duì)象副本。這樣就能保證線程的安全。
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、創(chuàng)建線程池 ExecutorService pool = Executors.newFixedThreadPool(5); //2、為線程池分配任務(wù) ThreadPoolTest threadPoolTest = new ThreadPoolTest(); for (int i = 0; i < 10; i++) { pool.submit(threadPoolTest); } //3、關(guān)閉線程池 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 { //避免內(nèi)存泄漏,使用完threadLocal后要調(diào)用remove方法清除數(shù)據(jù) threadLocal.remove(); } } } }
使用ThreadLocal能保證線程安全,且效率也是挺高的。適合高并發(fā)場(chǎng)景使用。
解決方案4:使用DateTimeFormatter代替SimpleDateFormat
使用DateTimeFormatter代替SimpleDateFormat(DateTimeFormatter是線程安全的,java 8+支持)
DateTimeFormatter介紹 傳送門:萬字博文教你搞懂java源碼的日期和時(shí)間相關(guān)用法
public class DateTimeFormatterDemoTest5 { private static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); public static void main(String[] args) { //1、創(chuàng)建線程池 ExecutorService pool = Executors.newFixedThreadPool(5); //2、為線程池分配任務(wù) ThreadPoolTest threadPoolTest = new ThreadPoolTest(); for (int i = 0; i < 10; i++) { pool.submit(threadPoolTest); } //3、關(guān)閉線程池 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能保證線程安全,且效率也是挺高的。適合高并發(fā)場(chǎng)景使用。
解決方案5:使用FastDateFormat 替換SimpleDateFormat
使用FastDateFormat 替換SimpleDateFormat(FastDateFormat 是線程安全的,Apache Commons Lang包支持,不受限于java版本)
public class DateTimeFormatterDemoTest5 { private static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); public static void main(String[] args) { //1、創(chuàng)建線程池 ExecutorService pool = Executors.newFixedThreadPool(5); //2、為線程池分配任務(wù) ThreadPoolTest threadPoolTest = new ThreadPoolTest(); for (int i = 0; i < 10; i++) { pool.submit(threadPoolTest); } //3、關(guān)閉線程池 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()+" 格式化失敗 "); } } } }
使用FastDateFormat能保證線程安全,且效率也是挺高的。適合高并發(fā)場(chǎng)景使用。
FastDateFormat源碼分析
Apache Commons Lang 3.5
//FastDateFormat @Overridepublic 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 方法里創(chuàng)建的,肯定不會(huì)出現(xiàn) setTime 的線程安全問題。這樣線程安全疑惑解決了。那還有性能問題要考慮?
我們來看下FastDateFormat是怎么獲取的
FastDateFormat.getInstance();FastDateFormat.getInstance(CHINESE_DATE_TIME_PATTERN);
看下對(duì)應(yīng)的源碼
/** * 獲得 FastDateFormat實(shí)例,使用默認(rèn)格式和地區(qū) * * @return FastDateFormat */ public static FastDateFormat getInstance() { return CACHE.getInstance(); } /** * 獲得 FastDateFormat 實(shí)例,使用默認(rèn)地區(qū) * 支持緩存 * * @param pattern 使用{@link java.text.SimpleDateFormat} 相同的日期格式 * @return FastDateFormat * @throws IllegalArgumentException 日期格式問題 */ public static FastDateFormat getInstance(final String pattern) { return CACHE.getInstance(pattern, null, null); }
這里有用到一個(gè)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 也是線程安全的。
實(shí)踐
/** * 年月格式 {@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值是格式,時(shí)區(qū)和locale(語境)三者都相同為相同的key。
結(jié)論
這個(gè)是阿里巴巴 java開發(fā)手冊(cè)中的規(guī)定:
1、不要定義為static變量,使用局部變量
2、加鎖:synchronized鎖和Lock鎖
3、使用ThreadLocal方式
4、使用DateTimeFormatter代替SimpleDateFormat(DateTimeFormatter是線程安全的,java 8+支持)
5、使用FastDateFormat 替換SimpleDateFormat(FastDateFormat 是線程安全的,Apache Commons Lang包支持,java8之前推薦此用法)
到此這篇關(guān)于java的SimpleDateFormat線程不安全的幾種解決方案的文章就介紹到這了,更多相關(guān)java SimpleDateFormat線程不安全內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java+swing實(shí)現(xiàn)經(jīng)典貪吃蛇游戲
貪吃蛇(也叫做貪食蛇)游戲是一款休閑益智類游戲,有PC和手機(jī)等多平臺(tái)版本。既簡(jiǎn)單又耐玩。本文將通過java的swing來實(shí)現(xiàn)這一游戲,需要的可以參考一下2022-01-01Java常用面板之JScrollPane滾動(dòng)面板實(shí)例詳解
這篇文章主要介紹了Java常用面板JScrollPane的簡(jiǎn)單介紹和一個(gè)相關(guān)實(shí)例,,需要的朋友可以參考下。2017-08-08java實(shí)現(xiàn)簡(jiǎn)單日期計(jì)算功能
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)簡(jiǎn)單日期計(jì)算功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-11-11Java可重入鎖的實(shí)現(xiàn)原理與應(yīng)用場(chǎng)景
今天小編就為大家分享一篇關(guān)于Java可重入鎖的實(shí)現(xiàn)原理與應(yīng)用場(chǎng)景,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-01-01Servlet的兩種創(chuàng)建方式(xml?注解)示例詳解
這篇文章主要為大家介紹了Servlet的兩種創(chuàng)建方式(xml?注解)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08Spring?Security實(shí)現(xiàn)基于RBAC的權(quán)限表達(dá)式動(dòng)態(tài)訪問控制的操作方法
這篇文章主要介紹了Spring?Security實(shí)現(xiàn)基于RBAC的權(quán)限表達(dá)式動(dòng)態(tài)訪問控制,資源權(quán)限表達(dá)式動(dòng)態(tài)權(quán)限控制在Spring Security也是可以實(shí)現(xiàn)的,首先開啟方法級(jí)別的注解安全控制,本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-04-04