Java ThreadLocal 線程安全問題解決方案
一、線程安全問題產(chǎn)生的原因
線程安全問題都是由全局變量及靜態(tài)變量引起的
二、線程安全問題
SimpleDateFormate sdf = new SimpleDateFormat();使用sdf.parse(dateStr);sdf.format(date);在sdf內(nèi)有一個(gè)對(duì)Caleadar對(duì)象的引用,在源碼sdf.parse(dateStr);源碼中calendar.clear();和calendar.getTime(); // 獲取calendar的時(shí)間

如果 線程A 調(diào)用了 sdf.parse(), 并且進(jìn)行了 calendar.clear()后還未執(zhí)行calendar.getTime()的時(shí)候,線程B又調(diào)用了sdf.parse(), 這時(shí)候線程B也執(zhí)行了sdf.clear()方法, 這樣就導(dǎo)致線程A的的calendar數(shù)據(jù)被清空了;
ThreadLocal是使用空間換時(shí)間,synchronized是使用時(shí)間換空間
使用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);
}
}
}
感謝閱讀本文,希望能幫助到大家,謝謝大家對(duì)本站的支持!
相關(guān)文章
Java設(shè)計(jì)模式常用的七大原則總結(jié)
今天給大家總結(jié)了Java設(shè)計(jì)模式的七大原則,主要有單一職責(zé)原則,接口隔離原則,依賴倒轉(zhuǎn)原則,里氏替換原則等,文中有非常詳細(xì)的介紹,需要的朋友可以參考下2021-06-06
Mybatis結(jié)果集自動(dòng)映射的實(shí)例代碼
在使用Mybatis時(shí),有的時(shí)候我們可以不用定義resultMap,而是直接在<select>語句上指定resultType。這個(gè)時(shí)候其實(shí)就用到了Mybatis的結(jié)果集自動(dòng)映射,下面通過本文給大家分享Mybatis結(jié)果集自動(dòng)映射的實(shí)例代碼,一起看看吧2017-02-02
解析ConcurrentHashMap: transfer方法源碼分析(難點(diǎn))
ConcurrentHashMap是由Segment數(shù)組結(jié)構(gòu)和HashEntry數(shù)組結(jié)構(gòu)組成。Segment的結(jié)構(gòu)和HashMap類似,是一種數(shù)組和鏈表結(jié)構(gòu),今天給大家普及java面試常見問題---ConcurrentHashMap知識(shí),一起看看吧2021-06-06
Spring?Boot?使用斷言讓你的代碼在上線前就通過“體檢”(最新整理)
斷言是一種編程技巧,用于在代碼中插入檢查點(diǎn),驗(yàn)證程序的狀態(tài)是否符合預(yù)期,如果斷言失敗,程序會(huì)拋出一個(gè)錯(cuò)誤,幫助你快速發(fā)現(xiàn)和修復(fù)bug,本文給大家介紹Spring?Boot?斷言:讓你的代碼在上線前就通過“體檢”,感興趣的朋友一起看看吧2025-03-03

