這篇文章將為大家詳細(xì)講解有關(guān)simpledateformat線(xiàn)程不安全的原因,小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
南澳ssl適用于網(wǎng)站、小程序/APP、API接口等需要進(jìn)行數(shù)據(jù)傳輸應(yīng)用場(chǎng)景,ssl證書(shū)未來(lái)市場(chǎng)廣闊!成為創(chuàng)新互聯(lián)的ssl證書(shū)銷(xiāo)售渠道,可以享受市場(chǎng)價(jià)格4-6折優(yōu)惠!如果有意向歡迎電話(huà)聯(lián)系或者加微信:18980820575(備注:SSL證書(shū)合作)期待與您的合作!
原因:在多線(xiàn)程環(huán)境下,當(dāng)多個(gè)線(xiàn)程同時(shí)使用相同的SimpleDateFormat對(duì)象(如static修飾)的話(huà),如調(diào)用format方法時(shí),多個(gè)線(xiàn)程會(huì)同時(shí)調(diào)用calender.setTime方法,導(dǎo)致time被別的線(xiàn)程修改,因此線(xiàn)程是不安全的。
本教程操作環(huán)境:windows7系統(tǒng)、java8版、DELL G3電腦。
線(xiàn)程不安全驗(yàn)證:
/** * SimpleDateFormat線(xiàn)程安全測(cè)試 * 〈功能詳細(xì)描述〉 * * @author 17090889 * @see [相關(guān)類(lèi)/方法](可選) * @since [產(chǎn)品/模塊版本] (可選) */ public class SimpleDateFormatTest { private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(10, 100, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<>(1000), new MyThreadFactory("SimpleDateFormatTest")); public void test() { while (true) { poolExecutor.execute(new 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(dateString.equals(dateString2)); } catch (ParseException e) { e.printStackTrace(); } } }); } }
輸出:
true false true true false
出現(xiàn)了false,說(shuō)明線(xiàn)程不安全
1、format方法
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition pos) { pos.beginIndex = pos.endIndex = 0; return format(date, toAppendTo, pos.getFieldDelegate()); } // 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); boolean useDateFormatSymbols = useDateFormatSymbols(); for (int i = 0; i < compiledPattern.length; ) { int tag = compiledPattern[i] >>> 8; int count = compiledPattern[i++] & 0xff; if (count == 255) { count = compiledPattern[i++] << 16; count |= compiledPattern[i++]; } switch (tag) { case TAG_QUOTE_ASCII_CHAR: toAppendTo.append((char)count); break; case TAG_QUOTE_CHARS: toAppendTo.append(compiledPattern, i, count); i += count; break; default: subFormat(tag, count, delegate, toAppendTo, useDateFormatSymbols); break; } } return toAppendTo; }
protected Calendar calendar;
可以看到,多個(gè)線(xiàn)程之間共享變量calendar,并修改calendar。因此在多線(xiàn)程環(huán)境下,當(dāng)多個(gè)線(xiàn)程同時(shí)使用相同的SimpleDateFormat對(duì)象(如static修飾)的話(huà),如調(diào)用format方法時(shí),多個(gè)線(xiàn)程會(huì)同時(shí)調(diào)用calender.setTime方法,導(dǎo)致time被別的線(xiàn)程修改,因此線(xiàn)程是不安全的。
此外,parse方法也是線(xiàn)程不安全的,parse方法實(shí)際調(diào)用的是CalenderBuilder的establish來(lái)進(jìn)行解析,其方法中主要步驟不是原子操作。
解決方案:
1、將SimpleDateFormat定義成局部變量
2、 加一把線(xiàn)程同步鎖:synchronized(lock)
3、使用ThreadLocal,每個(gè)線(xiàn)程都擁有自己的SimpleDateFormat對(duì)象副本。如:
/** * SimpleDateFormat線(xiàn)程安全測(cè)試 * 〈功能詳細(xì)描述〉 * * @author 17090889 * @see [相關(guān)類(lèi)/方法](可選) * @since [產(chǎn)品/模塊版本] (可選) */ public class SimpleDateFormatTest { private static final ThreadLocal<SimpleDateFormat> THREAD_LOCAL = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } }; // private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(10, 100, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<>(1000), new MyThreadFactory("SimpleDateFormatTest")); public void test() { while (true) { poolExecutor.execute(new Runnable() { @Override public void run() { SimpleDateFormat simpleDateFormat = THREAD_LOCAL.get(); if (simpleDateFormat == null) { 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(dateString.equals(dateString2)); } catch (ParseException e) { e.printStackTrace(); } finally { local.remove(); } } }); } } }
4、使用DateTimeFormatter代替SimpleDateFormat
DateTimeFormatter是線(xiàn)程安全的,默認(rèn)提供了很多格式化方法,也可以通過(guò)ofPattern方法創(chuàng)建自定義格式化方法。
(1)格式化日期示例:
LocalDateTime localDateTime = LocalDateTime.now(); System.out.println(localDateTime); // 2019-11-20T15:04:29.017 DateTimeFormatter dtf=DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"); String strDate=localDateTime.format(dtf); System.out.println(strDate); // 2019/23/20 15:23:46
(2)解析日期
DateTimeFormatter dtf=DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"); LocalDateTime localDateTime=LocalDateTime.parse("2019/11/20 15:23:46",dtf); System.out.println(localDateTime); // 2019-11-20T15:23:46
關(guān)于“simpledateformat線(xiàn)程不安全的原因”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。
名稱(chēng)欄目:simpledateformat線(xiàn)程不安全的原因
分享路徑:http://www.rwnh.cn/article32/jjsesc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制網(wǎng)站、微信小程序、做網(wǎng)站、域名注冊(cè)、App開(kāi)發(fā)、軟件開(kāi)發(fā)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)