日本不卡不码高清免费观看,久久国产精品久久w女人spa,黄色aa久久,三上悠亚国产精品一区二区三区

您的位置:首頁技術(shù)文章
文章詳情頁

java的SimpleDateFormat線程不安全的幾種解決方案

瀏覽:26日期:2023-02-13 11:27:06
目錄場景SimpleDateFormat線程為什么是線程不安全的呢?驗證SimpleDateFormat線程不安全解決方案解決方案1:不要定義為static變量,使用局部變量解決方案2:加鎖:synchronized鎖和Lock鎖 加synchronized鎖加Lock鎖解決方案3:使用ThreadLocal方式解決方案4:使用DateTimeFormatter代替SimpleDateFormat解決方案5:使用FastDateFormat 替換SimpleDateFormatFastDateFormat源碼分析實踐結(jié)論場景

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

但我們知道SimpleDateFormat是線程不安全的,處理時要特別小心,要加鎖或者不能定義為static,要在方法內(nèi)new出對象,再進(jìn)行格式化。很麻煩,而且重復(fù)地new出對象,也加大了內(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 listcalendar.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; }

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

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

java的SimpleDateFormat線程不安全的幾種解決方案

calb.establish(calendar)方法先后調(diào)用了cal.clear()cal.set(),先清理值,再設(shè)值。但是這兩個操作并不是原子性的,也沒有線程安全機(jī)制來保證,導(dǎo)致多線程并發(fā)時,可能會引起cal的值出現(xià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{@Overridepublic 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()+' 格式化失敗 ');}} }}

java的SimpleDateFormat線程不安全的幾種解決方案

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

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

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

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{@Overridepublic 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()+' 格式化失敗 ');}} }}

java的SimpleDateFormat線程不安全的幾種解決方案

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

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

SimpleDateFormat對象還是定義為全局變量,然后需要調(diào)用SimpleDateFormat進(jìn)行格式化時間時,再用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{@Overridepublic 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()+' 格式化失敗 ');}} }}

java的SimpleDateFormat線程不安全的幾種解決方案

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

加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{@Overridepublic 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();}} }}

java的SimpleDateFormat線程不安全的幾種解決方案

由結(jié)果可知,加Lock鎖也能保證線程安全。要注意的是,最后一定要釋放鎖,代碼里在finally里增加了lock.unlock();,保證釋放鎖。在高并發(fā)的情況下會影響性能。這種方案不建議在高并發(fā)場景下使用

解決方案3:使用ThreadLocal方式

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

public class SimpleDateFormatDemoTest4 {private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>(){@Overrideprotected 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{@Overridepublic 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();}} }}

java的SimpleDateFormat線程不安全的幾種解決方案

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

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

使用DateTimeFormatter代替SimpleDateFormat(DateTimeFormatter是線程安全的,java 8+支持)DateTimeFormatter介紹 傳送門:萬字博文教你搞懂java源碼的日期和時間相關(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{@Overridepublic 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()+' 格式化失敗 ');}}}}

java的SimpleDateFormat線程不安全的幾種解決方案

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

解決方案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{@Overridepublic 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ā)場景使用

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)建的,肯定不會出現(xiàn) setTime 的線程安全問題。這樣線程安全疑惑解決了。那還有性能問題要考慮?

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

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

看下對應(yīng)的源碼

/** * 獲得 FastDateFormat實例,使用默認(rèn)格式和地區(qū) * * @return FastDateFormat */public static FastDateFormat getInstance() { return CACHE.getInstance();}/** * 獲得 FastDateFormat 實例,使用默認(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);}

這里有用到一個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); ...}

java的SimpleDateFormat線程不安全的幾種解決方案

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

實踐

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

java的SimpleDateFormat線程不安全的幾種解決方案

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

java的SimpleDateFormat線程不安全的幾種解決方案

java的SimpleDateFormat線程不安全的幾種解決方案

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

結(jié)論

這個是阿里巴巴 java開發(fā)手冊中的規(guī)定:

java的SimpleDateFormat線程不安全的幾種解決方案

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)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: Java
相關(guān)文章:
日本不卡不码高清免费观看,久久国产精品久久w女人spa,黄色aa久久,三上悠亚国产精品一区二区三区
国产高清久久| 国产精品久久久久蜜臀 | 日韩精品a在线观看91| 欧美大黑bbbbbbbbb在线| 麻豆视频在线观看免费网站黄 | 欧美三级第一页| 久久爱www成人| 国产精品v日韩精品v欧美精品网站| 黑森林国产精品av| 天堂av一区| 日韩va欧美va亚洲va久久| 蜜臀精品一区二区三区在线观看 | 亚州av一区| 国产精品视频3p| 在线看片国产福利你懂的| 欧美天堂视频| 日韩一级网站| 国产日韩一区二区三区在线 | 蜜臀av在线播放一区二区三区 | 日产精品一区| 久久高清国产| 亚洲人成高清| 国产精品v亚洲精品v日韩精品| 首页国产精品| 日韩一区二区免费看| 国产伦理一区| 91久久久精品国产| 日韩精品一区二区三区中文| 国产成人免费| 亚洲精品人人| 三级小说欧洲区亚洲区| 日韩精品一级| 欧美+亚洲+精品+三区| 欧美日本不卡高清| 欧美粗暴jizz性欧美20| 日本亚洲视频| 久久97久久97精品免视看秋霞| 九九精品调教| 欧美久久一区二区三区| 999国产精品| 久久xxx视频| 亚洲丝袜美腿一区| 婷婷综合社区| 日韩精品2区| 久久精品国产成人一区二区三区| 丝瓜av网站精品一区二区| 蜜桃av在线播放| 国产成人免费视频网站视频社区| 日本在线成人| 国产精品日韩| 亚洲成人一区| 欧美www视频在线观看| 免费看日韩精品| aa亚洲婷婷| japanese国产精品| 欧美午夜精彩| 亚洲大片在线| 欧美精品一区二区三区精品| 欧美日韩视频网站| 亚洲综合电影| 性感美女一区二区在线观看| 日韩国产欧美一区二区| 高清av一区| 伊人网在线播放| 天堂资源在线亚洲| 午夜精品影院| 91高清一区| 蜜臀av一区二区在线免费观看| 日韩在线播放一区二区| 亚洲免费一区三区| 青草国产精品| 精品国产鲁一鲁****| 色婷婷色综合| 黑丝一区二区三区| 日韩精品一级中文字幕精品视频免费观看 | 日本精品国产| 麻豆久久一区二区| 久久99久久人婷婷精品综合| 毛片不卡一区二区| 麻豆久久久久久| 黑森林国产精品av| 亚洲二区三区不卡| 日韩高清不卡在线| 日韩av片子| 日韩在线一区二区| 久久女人天堂| 亚洲精品一二三区区别| 日本99精品| 日本综合字幕| 日韩高清不卡一区二区| 日韩毛片视频| 一区二区亚洲视频| 国产一区二区三区四区| 六月丁香综合| 久久午夜影院| 亚洲综合丁香| 精品久久久久中文字幕小说| 免费在线观看视频一区| 欧美xxxx中国| 青草国产精品| 蜜桃视频欧美| 久久精品女人| 97se亚洲| 蜜桃视频第一区免费观看| sm久久捆绑调教精品一区| 视频一区日韩| 国产午夜精品一区二区三区欧美 | 亚洲天堂av资源在线观看| 久久精品国产亚洲aⅴ| 老司机精品久久| 日韩免费久久| 国产精品99久久免费观看| 亚洲欧美视频| 亚洲婷婷在线| 久久激情一区| а√天堂8资源中文在线| 国产欧美一区二区色老头| 久久先锋影音| 亚洲深爱激情| 在线视频观看日韩| 国产一区丝袜| 久久中文字幕一区二区三区| 日本欧美韩国一区三区| 亚洲va久久久噜噜噜久久| 久久国产88| 亚洲精品综合| 日韩毛片一区| 欧美日韩va| 国产精品成人一区二区网站软件| 日韩精品欧美成人高清一区二区| 亚洲综合三区| 亚洲男人在线| 日韩精品成人在线观看| 欧美亚洲人成在线| 国产精品一区二区av交换| 国产欧美大片| 久久99影视| 久久精品动漫| 羞羞答答国产精品www一本| 蜜桃视频一区二区三区在线观看 | 国产精品自在| 首页国产精品| 国产精品av久久久久久麻豆网| 99成人在线| 日韩av在线免费观看不卡| 国产免费av一区二区三区| 九九久久国产| 精品一区在线| 亚洲精品无吗| 国产成人精品福利| 国产精品av一区二区| 日韩精品欧美成人高清一区二区| 国产精品啊v在线| 99精品视频在线观看免费播放| 在线亚洲自拍| 国产精品乱战久久久| 久久婷婷激情| 国产日韩视频在线| 国产精品99一区二区| 欧美另类中文字幕 | 亚洲一级网站| 国产伦一区二区三区| 欧美~级网站不卡| 欧美激情99| 中文字幕日韩欧美精品高清在线| 岛国精品一区| 久久精品二区三区| 日韩激情啪啪| 91精品一区国产高清在线gif| 国产午夜久久av| 亚洲网站视频| 国产福利91精品一区二区| 日本视频一区二区| 亚洲综合欧美| 在线亚洲人成| 久久国际精品| 亚洲一区二区免费在线观看| 热三久草你在线| 国产精品一级| 亚欧成人精品| 三级在线观看一区二区| 亚洲电影有码| 日韩欧美1区| 欧美激情精品| 国产亚洲一区二区三区不卡| 石原莉奈一区二区三区在线观看| 日韩中文欧美| 国产精品福利在线观看播放| 日本中文字幕视频一区| 日韩成人亚洲| 国产精品15p| 日本午夜精品一区二区三区电影| 欧美精品一区二区三区精品| 999国产精品永久免费视频app| 精品三级av| 麻豆精品国产91久久久久久| 久久精品国产99国产| 97精品国产| 播放一区二区| 国产日韩综合|