Java ThreadLocal 線程安全問題解決方案
一、線程安全問題產(chǎn)生的原因
線程安全問題都是由全局變量及靜態(tài)變量引起的
二、線程安全問題
SimpleDateFormate sdf = new SimpleDateFormat();使用sdf.parse(dateStr);sdf.format(date);在sdf內(nèi)有一個對Caleadar對象的引用,在源碼sdf.parse(dateStr);源碼中calendar.clear();和calendar.getTime(); // 獲取calendar的時間
如果 線程A 調(diào)用了 sdf.parse(), 并且進(jìn)行了 calendar.clear()后還未執(zhí)行calendar.getTime()的時候,線程B又調(diào)用了sdf.parse(), 這時候線程B也執(zhí)行了sdf.clear()方法, 這樣就導(dǎo)致線程A的的calendar數(shù)據(jù)被清空了;
ThreadLocal是使用空間換時間,synchronized是使用時間換空間
使用ThreadLocal解決線程安全:
public class ThreadLocalDateUtil { private static final String date_format = "yyyy-MM-dd HH:mm:ss"; private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>(); public static DateFormat getDateFormat() { DateFormat df = threadLocal.get(); if(df==null){ df = new SimpleDateFormat(date_format); threadLocal.set(df); } return df; } public static String formatDate(Date date) throws ParseException { return getDateFormat().format(date); } public static Date parse(String strDate) throws ParseException { return getDateFormat().parse(strDate); } }
使用synchronized解決方案:
public class DateSyncUtil { private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static String formatDate(Date date)throws ParseException{ synchronized(sdf){ return sdf.format(date); } } public static Date parse(String strDate) throws ParseException{ synchronized(sdf){ return sdf.parse(strDate); } } }
感謝閱讀本文,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
java MyBatis攔截器Inteceptor詳細(xì)介紹
這篇文章主要介紹了java MyBatis攔截器Inteceptor詳細(xì)介紹的相關(guān)資料,需要的朋友可以參考下2016-11-11Spring注解驅(qū)動之@EventListener注解使用方式
這篇文章主要介紹了Spring注解驅(qū)動之@EventListener注解使用方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09Java組件FileUpload上傳文件實現(xiàn)代碼
這篇文章主要為大家詳細(xì)介紹了Java組件FileUpload上傳文件實現(xiàn)代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-06-06SpringBoot @FixMethodOrder 如何調(diào)整單元測試順序
這篇文章主要介紹了SpringBoot @FixMethodOrder 調(diào)整單元測試順序方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09SpringCloud+MyBatis分頁處理(前后端分離)
這篇文章主要為大家詳細(xì)介紹了SpringCloud+MyBatis分頁處理,前后端分離,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-10-10