最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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)存開(kāi)銷(xiāo)。

SimpleDateFormat線程為什么是線程不安全的呢?

來(lái)看看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);
		...
    }

問(wèn)題就出在成員變量calendar,如果在使用SimpleDateFormat時(shí),用static定義,那SimpleDateFormat變成了共享變量。那SimpleDateFormat中的calendar就可以被多個(gè)線程訪問(wèn)到。

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è)線程訪問(wèn)到,存在線程不安全問(wèn)題。

我們?cè)賮?lái)看看**calb.establish(calendar)**的源碼

image-20210805827464

calb.establish(calendar)方法先后調(diào)用了cal.clear()cal.set(),先清理值,再設(shè)值。但是這兩個(gè)操作并不是原子性的,也沒(méi)有線程安全機(jī)制來(lái)保證,導(dǎo)致多線程并發(fā)時(shí),可能會(huì)引起cal的值出現(xiàn)問(wè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,說(shuō)明線程是不安全的。而且還拋異常,這個(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介紹 傳送門(mén):萬(wàn)字博文教你搞懂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 的線程安全問(wèn)題。這樣線程安全疑惑解決了。那還有性能問(wèn)題要考慮?

我們來(lái)看下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 日期格式問(wèn)題 
*/
public static FastDateFormat getInstance(final String pattern) {
    return CACHE.getInstance(pattern, null, null);
}

這里有用到一個(gè)CACHE,看來(lái)用了緩存,往下看

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(語(yǔ)境)三者都相同為相同的key。

結(jié)論

這個(gè)是阿里巴巴 java開(kāi)發(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)文章

最新評(píng)論

晋城| 同仁县| 和政县| 外汇| 漾濞| 旬阳县| 德令哈市| 万州区| 许昌县| 包头市| 蛟河市| 嘉禾县| 宁津县| 临漳县| 炉霍县| 磐安县| 新营市| 涟水县| 昌吉市| 菏泽市| 绿春县| 武汉市| 望城县| 天水市| 射阳县| 栾川县| 北碚区| 长垣县| 霍邱县| 蕲春县| 紫云| 库伦旗| 阿克陶县| 宜兰县| 乌审旗| 清水河县| 乌拉特中旗| 濮阳县| 玉门市| 钟山县| 武邑县|