一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務(wù)器之家 - 編程語言 - Java教程 - java的SimpleDateFormat線程不安全的幾種解決方案

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

2021-11-11 11:06小虛竹 Java教程

但我們知道SimpleDateFormat是線程不安全的,處理時(shí)要特別小心,要加鎖或者不能定義為static,要在方法內(nèi)new出對象,再進(jìn)行格式化,本文就介紹了幾種方法,感興趣的可以了解一下

 

場景

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

但我們知道SimpleDateFormat是線程不安全的,處理時(shí)要特別小心,要加鎖或者不能定義為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 list
        calendar.setTime(date);
		...
    }

問題就出在成員變量calendar,如果在使用SimpleDateFormat時(shí),用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ā)時(shí),可能會引起cal的值出現(xiàn)問題了。

 

驗(yà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{

        @Override
        public 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時(shí),再定義為局部變量。就能保證線程安全。

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{

		@Override
		public 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ā)場景下使用,因?yàn)闀?chuàng)建大量的SimpleDateFormat對象,影響性能。

 

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

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

		@Override
		public 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鎖,
同一時(shí)刻只有一個線程能執(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{

		@Override
		public 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>(){
		@Override
		protected 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{

		@Override
		public 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源碼的日期和時(shí)間相關(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{

		@Override
		public 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{

		@Override
		public 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實(shí)例,使用默認(rèn)格式和地區(qū) *
 * @return FastDateFormat 
*/
public static FastDateFormat getInstance() {
    return CACHE.getInstance();
}
/**
 * 獲得 FastDateFormat 實(shí)例,使用默認(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 也是線程安全的。

 

實(shí)踐

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

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

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

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

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

如圖可證,是使用了ConcurrentMap 做緩存。且key值是格式,時(shí)區(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ù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!

原文鏈接:https://blog.csdn.net/shi_hong_fei_hei/article/details/119422646

延伸 · 閱讀

精彩推薦
  • Java教程xml與Java對象的轉(zhuǎn)換詳解

    xml與Java對象的轉(zhuǎn)換詳解

    這篇文章主要介紹了xml與Java對象的轉(zhuǎn)換詳解的相關(guān)資料,需要的朋友可以參考下...

    Java教程網(wǎng)2942020-09-17
  • Java教程Java實(shí)現(xiàn)搶紅包功能

    Java實(shí)現(xiàn)搶紅包功能

    這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)搶紅包功能,采用多線程模擬多人同時(shí)搶紅包,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙...

    littleschemer13532021-05-16
  • Java教程Java使用SAX解析xml的示例

    Java使用SAX解析xml的示例

    這篇文章主要介紹了Java使用SAX解析xml的示例,幫助大家更好的理解和學(xué)習(xí)使用Java,感興趣的朋友可以了解下...

    大行者10067412021-08-30
  • Java教程Java BufferWriter寫文件寫不進(jìn)去或缺失數(shù)據(jù)的解決

    Java BufferWriter寫文件寫不進(jìn)去或缺失數(shù)據(jù)的解決

    這篇文章主要介紹了Java BufferWriter寫文件寫不進(jìn)去或缺失數(shù)據(jù)的解決方案,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望...

    spcoder14552021-10-18
  • Java教程升級IDEA后Lombok不能使用的解決方法

    升級IDEA后Lombok不能使用的解決方法

    最近看到提示IDEA提示升級,尋思已經(jīng)有好久沒有升過級了。升級完畢重啟之后,突然發(fā)現(xiàn)好多錯誤,本文就來介紹一下如何解決,感興趣的可以了解一下...

    程序猿DD9332021-10-08
  • Java教程小米推送Java代碼

    小米推送Java代碼

    今天小編就為大家分享一篇關(guān)于小米推送Java代碼,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧...

    富貴穩(wěn)中求8032021-07-12
  • Java教程20個非常實(shí)用的Java程序代碼片段

    20個非常實(shí)用的Java程序代碼片段

    這篇文章主要為大家分享了20個非常實(shí)用的Java程序片段,對java開發(fā)項(xiàng)目有所幫助,感興趣的小伙伴們可以參考一下 ...

    lijiao5352020-04-06
  • Java教程Java8中Stream使用的一個注意事項(xiàng)

    Java8中Stream使用的一個注意事項(xiàng)

    最近在工作中發(fā)現(xiàn)了對于集合操作轉(zhuǎn)換的神器,java8新特性 stream,但在使用中遇到了一個非常重要的注意點(diǎn),所以這篇文章主要給大家介紹了關(guān)于Java8中S...

    阿杜7482021-02-04
主站蜘蛛池模板: 国产精品拍拍拍福利在线观看 | ova巨公主催眠1在线观看 | 青青青国产精品国产精品久久久久 | 好大用力深一点视频 | 精品免费久久久久久成人影院 | 亚洲国产在| 亚洲人成网站在线观看90影院 | 四虎影视在线影院在线观看 | 久久免费看少妇高潮A片特爽 | 国产51 | 亚洲网站在线看 | 114毛片免费观看网站 | 日韩亚洲欧美理论片 | 国产极品精频在线观看 | 免费高清视频日本 | 夫妇交换小说 | 99 久久99久久精品免观看 | 国产高清小视频 | 精品一区二区三区五区六区七区 | 91入口免费网站大全 | 亚洲视频免费 | 隔壁的漂亮邻居hd中文 | 色综合久久夜色精品国产 | 国产趴着打光屁股sp抽打 | japaneseles女同专区| sp啪啪调教打屁股网站 | 秋葵丝瓜茄子草莓榴莲樱桃 | 免费观看视频高清在线 | 高h文3p双龙 | 国产精品天天影视久久综合网 | 四缺一的小说 | xx18美女美国 | 日本成人高清视频 | 特黄特色大片免费高清视频 | 青草国产福利视频免费观看 | 丰满岳乱妇在线观看视频国产 | 亚洲www在线| 被老头操| 久久亚洲精品成人 | 欧美╳bbbb| 超鹏97国语 |