欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

場(chǎng)景

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

但我們知道SimpleDateFormat是線程不安全的,處理時(shí)要特別小心,要加鎖或者不能定義為static,要在方法內(nèi)new出對(duì)象,再進(jìn)行格式化。很麻煩,而且重復(fù)地new出對(duì)象,也加大了內(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就可以被多個(gè)線程訪問到。

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可以被多個(gè)線程訪問到,存在線程不安全問題。

我們?cè)賮砜纯?*calb.establish(calendar)**的源碼

image-20210805827464

calb.establish(calendar)方法先后調(diào)用了cal.clear()cal.set(),先清理值,再設(shè)值。但是這兩個(gè)操作并不是原子性的,也沒有線程安全機(jī)制來保證,導(dǎo)致多線程并發(fā)時(shí),可能會(huì)引起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()+" 格式化失敗 ");
				}
        }
    }
}

image-20210805754416

出現(xiàn)了兩次false,說明線程是不安全的。而且還拋異常,這個(gè)就嚴(yán)重了。

解決方案

解決方案1:不要定義為static變量,使用局部變量

就是要使用SimpleDateFormat對(duì)象進(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()+" 格式化失敗 ");
			}
		}
    }
}

image-20210805936439

由圖可知,已經(jīng)保證了線程安全,但這種方案不建議在高并發(fā)場(chǎng)景下使用,因?yàn)闀?huì)創(chuàng)建大量的SimpleDateFormat對(duì)象,影響性能。

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

SimpleDateFormat對(duì)象還是定義為全局變量,然后需要調(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()+" 格式化失敗 ");
			}
		}
    }
}

image-2021080591591

如圖所示,線程是安全的。定義了全局變量SimpleDateFormat,減少了創(chuàng)建大量SimpleDateFormat對(duì)象的損耗。但是使用synchronized鎖,
同一時(shí)刻只有一個(gè)線程能執(zhí)行鎖住的代碼塊,在高并發(fā)的情況下會(huì)影響性能。但這種方案不建議在高并發(fā)場(chǎng)景下使用

加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();
			}
		}
    }
}

image-20210805940496

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

解決方案3:使用ThreadLocal方式

使用ThreadLocal保證每一個(gè)線程有SimpleDateFormat對(duì)象副本。這樣就能保證線程的安全。

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();
			}
		}
    }
}

image-202108059729

使用ThreadLocal能保證線程安全,且效率也是挺高的。適合高并發(fā)場(chǎng)景使用。

解決方案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()+" 格式化失敗 ");
			}
		}
	}
}

image-2021080591443373

使用DateTimeFormatter能保證線程安全,且效率也是挺高的。適合高并發(fā)場(chǎng)景使用。

解決方案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ā)場(chǎng)景使用

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)建的,肯定不會(huì)出現(xiàn) setTime 的線程安全問題。這樣線程安全疑惑解決了。那還有性能問題要考慮?

我們來看下FastDateFormat是怎么獲取的

FastDateFormat.getInstance();FastDateFormat.getInstance(CHINESE_DATE_TIME_PATTERN);

看下對(duì)應(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);
}

這里有用到一個(gè)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);
    ...
}

image-20210728914309

在getInstance 方法中加了ConcurrentMap 做緩存,提高了性能。且我們知道ConcurrentMap 也是線程安全的。

實(shí)踐

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

image-2021072895013629

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

image-20210728205104833

image-2021072895259113

如圖可證,是使用了ConcurrentMap 做緩存。且key值是格式,時(shí)區(qū)和locale(語境)三者都相同為相同的key。

結(jié)論

這個(gè)是阿里巴巴 java開發(fā)手冊(cè)中的規(guī)定:

img

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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Spring Bean生命周期之屬性賦值階段詳解

    Spring Bean生命周期之屬性賦值階段詳解

    這篇文章主要為大家詳細(xì)介紹了Spring Bean生命周期之屬性賦值階段,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2022-03-03
  • Java+swing實(shí)現(xiàn)經(jīng)典貪吃蛇游戲

    Java+swing實(shí)現(xiàn)經(jīng)典貪吃蛇游戲

    貪吃蛇(也叫做貪食蛇)游戲是一款休閑益智類游戲,有PC和手機(jī)等多平臺(tái)版本。既簡(jiǎn)單又耐玩。本文將通過java的swing來實(shí)現(xiàn)這一游戲,需要的可以參考一下
    2022-01-01
  • Java常用面板之JScrollPane滾動(dòng)面板實(shí)例詳解

    Java常用面板之JScrollPane滾動(dòng)面板實(shí)例詳解

    這篇文章主要介紹了Java常用面板JScrollPane的簡(jiǎn)單介紹和一個(gè)相關(guān)實(shí)例,,需要的朋友可以參考下。
    2017-08-08
  • java實(shí)現(xiàn)簡(jiǎn)單日期計(jì)算功能

    java實(shí)現(xiàn)簡(jiǎn)單日期計(jì)算功能

    這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)簡(jiǎn)單日期計(jì)算功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-11-11
  • Java并發(fā)線程池實(shí)例分析講解

    Java并發(fā)線程池實(shí)例分析講解

    這篇文章主要介紹了Java并發(fā)線程池實(shí)例,線程池——控制線程創(chuàng)建、釋放,并通過某種策略嘗試復(fù)用線程去執(zhí)行任務(wù)的一個(gè)管理框架,從而實(shí)現(xiàn)線程資源與任務(wù)之間一種平衡
    2023-02-02
  • MyBatis快速入門

    MyBatis快速入門

    MyBatis是支持普通SQL查詢,存儲(chǔ)過程和高級(jí)映射的優(yōu)秀持久層框架。MyBatis消除了幾乎所有的JDBC代碼和參數(shù)的手工設(shè)置以及結(jié)果集的檢索。想要學(xué)好它,那就要從MyBatis基礎(chǔ)知識(shí)學(xué)起,下面跟著小編一起來看下吧
    2017-03-03
  • Java可重入鎖的實(shí)現(xiàn)原理與應(yīng)用場(chǎng)景

    Java可重入鎖的實(shí)現(xiàn)原理與應(yīng)用場(chǎng)景

    今天小編就為大家分享一篇關(guān)于Java可重入鎖的實(shí)現(xiàn)原理與應(yīng)用場(chǎng)景,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧
    2019-01-01
  • Servlet的兩種創(chuàng)建方式(xml?注解)示例詳解

    Servlet的兩種創(chuàng)建方式(xml?注解)示例詳解

    這篇文章主要為大家介紹了Servlet的兩種創(chuàng)建方式(xml?注解)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-08-08
  • Spring?Security實(shí)現(xiàn)基于RBAC的權(quán)限表達(dá)式動(dòng)態(tài)訪問控制的操作方法

    Spring?Security實(shí)現(xiàn)基于RBAC的權(quán)限表達(dá)式動(dòng)態(tài)訪問控制的操作方法

    這篇文章主要介紹了Spring?Security實(shí)現(xiàn)基于RBAC的權(quán)限表達(dá)式動(dòng)態(tài)訪問控制,資源權(quán)限表達(dá)式動(dòng)態(tài)權(quán)限控制在Spring Security也是可以實(shí)現(xiàn)的,首先開啟方法級(jí)別的注解安全控制,本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2022-04-04
  • springboot使用過濾器詳解

    springboot使用過濾器詳解

    本文主要介紹了過濾器的基本概念,過濾器的生命周期,以及如何通過注解方式和非注解方式實(shí)現(xiàn)過濾器,過濾器是客戶端與服務(wù)器資源文件之間的一道過濾網(wǎng),能夠幫助我們過濾不符合要求的請(qǐng)求,通常用作Session校驗(yàn)
    2024-10-10

最新評(píng)論