电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

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

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

在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 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; }

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

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

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

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{@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線程不安全的幾種解決方案

出現了兩次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{@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線程不安全的幾種解決方案

由圖可知,已經保證了線程安全,但這種方案不建議在高并發場景下使用,因為會創建大量的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{@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,減少了創建大量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{@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線程不安全的幾種解決方案

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

解決方案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、創建線程池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{@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 {//避免內存泄漏,使用完threadLocal后要調用remove方法清除數據threadLocal.remove();}} }}

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

使用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{@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能保證線程安全,且效率也是挺高的。適合高并發場景使用。

解決方案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、創建線程池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{@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能保證線程安全,且效率也是挺高的。適合高并發場景使用

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 方法里創建的,肯定不會出現 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 < 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值是格式,時區和locale(語境)三者都相同為相同的key。

結論

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

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

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

2、加鎖:synchronized鎖和Lock鎖

3、使用ThreadLocal方式

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

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

到此這篇關于java的SimpleDateFormat線程不安全的幾種解決方案的文章就介紹到這了,更多相關java SimpleDateFormat線程不安全內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Java
相關文章:
主站蜘蛛池模板: 净化板-洁净板-净化板价格-净化板生产厂家-山东鸿星新材料科技股份有限公司 | UV固化机_UVLED光固化机_UV干燥机生产厂家-上海冠顶公司专业生产UV固化机设备 | 山东钢衬塑罐_管道_反应釜厂家-淄博富邦滚塑防腐设备科技有限公司 | 洗地机_全自动洗地机_手推式洗地机【上海滢皓环保】 | 杜康白酒加盟_杜康酒代理_杜康酒招商加盟官网_杜康酒厂加盟总代理—杜康酒神全国运营中心 | 河南包装袋厂家_河南真空袋批发价格_河南服装袋定制-恒源达包装制品 | Type-c防水母座|贴片母座|耳机接口|Type-c插座-深圳市步步精科技有限公司 | 云南成考网_云南成人高考报名网| 小型高低温循环试验箱-可程式高低温湿热交变试验箱-东莞市拓德环境测试设备有限公司 | 电缆接头-防爆电缆接头-格兰头-金属电缆接头-防爆填料函 | 北京开业庆典策划-年会活动策划公司-舞龙舞狮团大鼓表演-北京盛乾龙狮鼓乐礼仪庆典策划公司 | 电镀整流器_微弧氧化电源_高频电解电源_微弧氧化设备厂家_深圳开瑞节能 | sfp光模块,高速万兆光模块工厂-性价比更高的光纤模块制造商-武汉恒泰通 | 动库网动库商城-体育用品专卖店:羽毛球,乒乓球拍,网球,户外装备,运动鞋,运动包,运动服饰专卖店-正品运动品网上商城动库商城网 - 动库商城 | 施工围挡-施工PVC围挡-工程围挡-深圳市旭东钢构技术开发有限公司 | 标策网-专注公司商业知识服务、助力企业发展 | 破碎机_上海破碎机_破碎机设备_破碎机厂家-上海山卓重工机械有限公司 | 披萨石_披萨盘_电器家电隔热绵加工定制_佛山市南海区西樵南方综合保温材料厂 | 多米诺-多米诺世界纪录团队-多米诺世界-多米诺团队培训-多米诺公关活动-多米诺创意广告-多米诺大型表演-多米诺专业赛事 | 100_150_200_250_300_350_400公斤压力空气压缩机-舰艇航天配套厂家 | 热风机_工业热风机生产厂家上海冠顶公司提供专业热风机图片价格实惠 | 进口便携式天平,外校_十万分之一分析天平,奥豪斯工业台秤,V2000防水秤-重庆珂偌德科技有限公司(www.crdkj.com) | 河南新乡德诚生产厂家主营震动筛,振动筛设备,筛机,塑料震动筛选机 | 常州减速机_减速机厂家_常州市减速机厂有限公司 | 挤出机_橡胶挤出机_塑料挤出机_胶片冷却机-河北伟源橡塑设备有限公司 | 液压油缸-液压站生产厂家-洛阳泰诺液压科技有限公司 | YJLV22铝芯铠装电缆-MYPTJ矿用高压橡套电缆-天津市电缆总厂 | 真空包装机-诸城市坤泰食品机械有限公司 | 厂房出售_厂房仓库出租_写字楼招租_土地出售-中苣招商网-中苣招商网 | 艺术生文化课培训|艺术生文化课辅导冲刺-济南启迪学校 | 螺纹三通快插接头-弯通快插接头-宁波舜驰气动科技有限公司 | 数码听觉统合训练系统-儿童感觉-早期言语评估与训练系统-北京鑫泰盛世科技发展有限公司 | 纸塑分离机-纸塑分离清洗机设备-压力筛-碎浆机厂家金双联环保 | 开云(中国)Kaiyun·官方网站-登录入口 | 上海盐水喷雾试验机_两厢式冷热冲击试验箱-巨怡环试 | 溶氧传感器-pH传感器|哈美顿(hamilton) | 高防护蠕动泵-多通道灌装系统-高防护蠕动泵-www.bjhuiyufluid.com慧宇伟业(北京)流体设备有限公司 | 聚合甘油__盐城市飞龙油脂有限公司| 代办建筑资质升级-建筑资质延期就找上海国信启航 | 大型工业风扇_工业大风扇_大吊扇_厂房车间降温-合昌大风扇 | SRRC认证_电磁兼容_EMC测试整改_FCC认证_SDOC认证-深圳市环测威检测技术有限公司 |