主頁 > 後端開發 > Simple Date Format類到底為啥不是執行緒安全的?

Simple Date Format類到底為啥不是執行緒安全的?

2023-06-06 07:45:11 後端開發

摘要:我們就一起看下在高并發下Simple Date Format類為何會出現安全問題,以及如何解決Simple Date Format類的安全問題,

本文分享自華為云社區《【高并發】SimpleDateFormat類到底為啥不是執行緒安全的?》,作者:冰 河,

首先問下大家:你使用的Simple Date Format類還安全嗎?為什么說Simple Date Format 類不是執行緒安全的?帶著問題從本文中尋求答案,

提起Simple Date Format 類,想必做過Java開發的童鞋都不會感到陌生,沒錯,它就是Java中提供的日期時間的轉化類,這里,為什么說Simple Date Format 類有執行緒安全問題呢?有些小伙伴可能會提出疑問:我們生產環境上一直在使用Simple Date Format 類來決議和格式化日期和時間型別的資料,一直都沒有問題啊!我的回答是:沒錯,那是因為你們的系統達不到Simple Date Format 類出現問題的并發量,也就是說你們的系統沒啥負載!

接下來,我們就一起看下在高并發下Simple Date Format 類為何會出現安全問題,以及如何解決 Simple Date Format 類的安全問題,

重現 Simple Date Format類的執行緒安全問題

為了重現Simple Date Format類的執行緒安全問題,一種比較簡單的方式就是使用執行緒池結合Java并發包中的Count Down Latch類和Semaphore類來重現執行緒安全問題,

有關Count Down Latch 類和Semaphore類的具體用法和底層原理與原始碼決議在【高并發專題】后文會深度分析,這里,大家只需要知道 Count Down Latch 類可以使一個執行緒等待其他執行緒各自執行完畢后再執行,而Semaphore類可以理解為一個計數信號量,必須由獲取它的執行緒釋放,經常用來限制訪問某些資源的執行緒數量,例如限流等,

好了,先來看下重現Simple Date Format 類的執行緒安全問題的代碼,如下所示,

package io.binghe.concurrent.lab06;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
 * @author binghe
 * @version 1.0.0
 * @description 測驗SimpleDateFormat的執行緒不安全問題
 */
public class SimpleDateFormatTest01 {
 //執行總次數
 private static final int EXECUTE_COUNT = 1000;
 //同時運行的執行緒數量
 private static final int THREAD_COUNT = 20;
 //SimpleDateFormat物件
 private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
 public static void main(String[] args) throws InterruptedException {
 final Semaphore semaphore = new Semaphore(THREAD_COUNT);
 final CountDownLatch countDownLatch = new CountDownLatch(EXECUTE_COUNT);
 ExecutorService executorService = Executors.newCachedThreadPool();
 for (int i = 0; i < EXECUTE_COUNT; i++){
 executorService.execute(() -> {
 try {
 semaphore.acquire();
 try {
 simpleDateFormat.parse("2020-01-01");
 } catch (ParseException e) {
 System.out.println("執行緒:" + Thread.currentThread().getName() + " 格式化日期失敗");
 e.printStackTrace();
 System.exit(1);
 }catch (NumberFormatException e){
 System.out.println("執行緒:" + Thread.currentThread().getName() + " 格式化日期失敗");
 e.printStackTrace();
 System.exit(1);
 }
 semaphore.release();
 } catch (InterruptedException e) {
 System.out.println("信號量發生錯誤");
 e.printStackTrace();
 System.exit(1);
 }
 countDownLatch.countDown();
 });
 }
 countDownLatch.await();
 executorService.shutdown();
 System.out.println("所有執行緒格式化日期成功");
 }
}

可以看到,在SimpleDateFormatTest01類中,首先定義了兩個常量,一個是程式執行的總次數,一個是同時運行的執行緒數量,程式中結合執行緒池和Count Down Latch類與Semaphore類來模擬高并發的業務場景,其中,有關日期轉化的代碼只有如下一行,

simpleDateFormat.parse("2020-01-01");

當程式捕獲到例外時,列印相關的資訊,并退出整個程式的運行,當程式正確運行后,會列印“所有執行緒格式化日期成功”,

運行程式輸出的結果資訊如下所示,

Exception in thread "pool-1-thread-4" Exception in thread "pool-1-thread-1" Exception in thread "pool-1-thread-2" 執行緒:pool-1-thread-7 格式化日期失敗
執行緒:pool-1-thread-9 格式化日期失敗
執行緒:pool-1-thread-10 格式化日期失敗
Exception in thread "pool-1-thread-3" Exception in thread "pool-1-thread-5" Exception in thread "pool-1-thread-6" 執行緒:pool-1-thread-15 格式化日期失敗
執行緒:pool-1-thread-21 格式化日期失敗
Exception in thread "pool-1-thread-23" 執行緒:pool-1-thread-16 格式化日期失敗
執行緒:pool-1-thread-11 格式化日期失敗
java.lang.ArrayIndexOutOfBoundsException
執行緒:pool-1-thread-27 格式化日期失敗
at java.lang.System.arraycopy(Native Method)
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:597)
at java.lang.StringBuffer.append(StringBuffer.java:367)
at java.text.DigitList.getLong(DigitList.java:191)執行緒:pool-1-thread-25 格式化日期失敗
at java.text.DecimalFormat.parse(DecimalFormat.java:2084)
at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1869)
at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)
執行緒:pool-1-thread-14 格式化日期失敗
at java.text.DateFormat.parse(DateFormat.java:364)
at io.binghe.concurrent.lab06.SimpleDateFormatTest01.lambda$main$0(SimpleDateFormatTest01.java:47)
執行緒:pool-1-thread-13 格式化日期失敗at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
執行緒:pool-1-thread-20 格式化日期失敗at java.lang.Long.parseLong(Long.java:601)
at java.lang.Long.parseLong(Long.java:631)
at java.text.DigitList.getLong(DigitList.java:195)
at java.text.DecimalFormat.parse(DecimalFormat.java:2084)
at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:2162)
at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)
at java.text.DateFormat.parse(DateFormat.java:364)
at io.binghe.concurrent.lab06.SimpleDateFormatTest01.lambda$main$0(SimpleDateFormatTest01.java:47)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:601)
at java.lang.Long.parseLong(Long.java:631)
at java.text.DigitList.getLong(DigitList.java:195)
at java.text.DecimalFormat.parse(DecimalFormat.java:2084)
at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1869)
at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)
at java.text.DateFormat.parse(DateFormat.java:364)
Process finished with exit code 1

說明,在高并發下使用Simple Date Format 類格式化日期時拋出了例外,Simple Date Forma t類不是執行緒安全的!!!

接下來,我們就看下,Simple Date Format 類為何不是執行緒安全的,

Simple Date Format 類為何不是執行緒安全的?

那么,接下來,我們就一起來看看真正引起Simple Date Format類執行緒不安全的根本原因,

通過查看Simple Date Format類的原始碼,我們得知:Simple Date Format是繼承自Date Format類,Date Format類中維護了一個全域的Calendar變數,如下所示,

/**
  * The {@link Calendar} instance used for calculating the date-time fields
  * and the instant of time. This field is used for both formatting and
  * parsing.
  *
  * <p>Subclasses should initialize this field to a {@link Calendar}
  * appropriate for the {@link Locale} associated with this
  * <code>DateFormat</code>.
  * @serial
  */
protected Calendar calendar;

從注釋可以看出,這個Calendar物件既用于格式化也用于決議日期時間,接下來,我們再查看parse()方法接近最后的部分,

@Override
public Date parse(String text, ParsePosition pos){
    ################此處省略N行代碼##################
 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;
}

可見,最后的回傳值是通過呼叫CalendarBuilder.establish()方法獲得的,而這個方法的引數正好就是前面的Calendar物件,

接下來,我們再來看看CalendarBuilder.establish()方法,如下所示,

Calendar establish(Calendar cal) {
 boolean weekDate = isSet(WEEK_YEAR)
 && field[WEEK_YEAR] > field[YEAR];
 if (weekDate && !cal.isWeekDateSupported()) {
 // Use YEAR instead
 if (!isSet(YEAR)) {
 set(YEAR, field[MAX_FIELD + WEEK_YEAR]);
 }
 weekDate = false;
 }
 cal.clear();
 // Set the fields from the min stamp to the max stamp so that
 // the field resolution works in the Calendar.
 for (int stamp = MINIMUM_USER_STAMP; stamp < nextStamp; stamp++) {
 for (int index = 0; index <= maxFieldIndex; index++) {
 if (field[index] == stamp) {
 cal.set(index, field[MAX_FIELD + index]);
 break;
 }
 }
 }
 if (weekDate) {
 int weekOfYear = isSet(WEEK_OF_YEAR) ? field[MAX_FIELD + WEEK_OF_YEAR] : 1;
 int dayOfWeek = isSet(DAY_OF_WEEK) ?
 field[MAX_FIELD + DAY_OF_WEEK] : cal.getFirstDayOfWeek();
 if (!isValidDayOfWeek(dayOfWeek) && cal.isLenient()) {
 if (dayOfWeek >= 8) {
 dayOfWeek--;
 weekOfYear += dayOfWeek / 7;
 dayOfWeek = (dayOfWeek % 7) + 1;
 } else {
 while (dayOfWeek <= 0) {
 dayOfWeek += 7;
 weekOfYear--;
 }
 }
 dayOfWeek = toCalendarDayOfWeek(dayOfWeek);
 }
 cal.setWeekDate(field[MAX_FIELD + WEEK_YEAR], weekOfYear, dayOfWeek);
 }
 return cal;
}

在CalendarBuilder.establish()方法中先后呼叫了cal.clear()與cal.set(),也就是先清除cal物件中設定的值,再重新設定新的值,由于Calendar內部并沒有執行緒安全機制,并且這兩個操作也都不是原子性的,所以當多個執行緒同時操作一個SimpleDateFormat時就會引起cal的值混亂,類似地, format()方法也存在同樣的問題,

因此, SimpleDateFormat類不是執行緒安全的根本原因是:DateFormat類中的Calendar物件被多執行緒共享,而Calendar物件本身不支持執行緒安全,

那么,得知了SimpleDateFormat類不是執行緒安全的,以及造成SimpleDateFormat類不是執行緒安全的原因,那么如何解決這個問題呢?接下來,我們就一起探討下如何解決SimpleDateFormat類在高并發場景下的執行緒安全問題,

解決SimpleDateFormat類的執行緒安全問題

解決SimpleDateFormat類在高并發場景下的執行緒安全問題可以有多種方式,這里,就列舉幾個常用的方式供參考,大家也可以在評論區給出更多的解決方案,

1.區域變數法

最簡單的一種方式就是將SimpleDateFormat類物件定義成區域變數,如下所示的代碼,將SimpleDateFormat類物件定義在parse(String)方法的上面,即可解決問題,

package io.binghe.concurrent.lab06;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
 * @author binghe
 * @version 1.0.0
 * @description 區域變數法解決SimpleDateFormat類的執行緒安全問題
 */
public class SimpleDateFormatTest02 {
 //執行總次數
 private static final int EXECUTE_COUNT = 1000;
 //同時運行的執行緒數量
 private static final int THREAD_COUNT = 20;
 public static void main(String[] args) throws InterruptedException {
 final Semaphore semaphore = new Semaphore(THREAD_COUNT);
 final CountDownLatch countDownLatch = new CountDownLatch(EXECUTE_COUNT);
 ExecutorService executorService = Executors.newCachedThreadPool();
 for (int i = 0; i < EXECUTE_COUNT; i++){
 executorService.execute(() -> {
 try {
 semaphore.acquire();
 try {
 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
 simpleDateFormat.parse("2020-01-01");
 } catch (ParseException e) {
 System.out.println("執行緒:" + Thread.currentThread().getName() + " 格式化日期失敗");
 e.printStackTrace();
 System.exit(1);
 }catch (NumberFormatException e){
 System.out.println("執行緒:" + Thread.currentThread().getName() + " 格式化日期失敗");
 e.printStackTrace();
 System.exit(1);
 }
 semaphore.release();
 } catch (InterruptedException e) {
 System.out.println("信號量發生錯誤");
 e.printStackTrace();
 System.exit(1);
 }
 countDownLatch.countDown();
 });
 }
 countDownLatch.await();
 executorService.shutdown();
 System.out.println("所有執行緒格式化日期成功");
 }
}

此時運行修改后的程式,輸出結果如下所示,

所有執行緒格式化日期成功

至于在高并發場景下使用區域變數為何能解決執行緒的安全問題,會在【JVM專題】的JVM記憶體模式相關內容中深入剖析,這里不做過多的介紹了,

當然,這種方式在高并發下會創建大量的SimpleDateFormat類物件,影響程式的性能,所以,這種方式在實際生產環境不太被推薦,

2.synchronized鎖方式

將SimpleDateFormat類物件定義成全域靜態變數,此時所有執行緒共享SimpleDateFormat類物件,此時在呼叫格式化時間的方法時,對SimpleDateFormat物件進行同步即可,代碼如下所示,

package io.binghe.concurrent.lab06;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
 * @author binghe
 * @version 1.0.0
 * @description 通過Synchronized鎖解決SimpleDateFormat類的執行緒安全問題
 */
public class SimpleDateFormatTest03 {
 //執行總次數
 private static final int EXECUTE_COUNT = 1000;
 //同時運行的執行緒數量
 private static final int THREAD_COUNT = 20;
 //SimpleDateFormat物件
 private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
 public static void main(String[] args) throws InterruptedException {
 final Semaphore semaphore = new Semaphore(THREAD_COUNT);
 final CountDownLatch countDownLatch = new CountDownLatch(EXECUTE_COUNT);
 ExecutorService executorService = Executors.newCachedThreadPool();
 for (int i = 0; i < EXECUTE_COUNT; i++){
 executorService.execute(() -> {
 try {
 semaphore.acquire();
 try {
 synchronized (simpleDateFormat){
 simpleDateFormat.parse("2020-01-01");
 }
 } catch (ParseException e) {
 System.out.println("執行緒:" + Thread.currentThread().getName() + " 格式化日期失敗");
 e.printStackTrace();
 System.exit(1);
 }catch (NumberFormatException e){
 System.out.println("執行緒:" + Thread.currentThread().getName() + " 格式化日期失敗");
 e.printStackTrace();
 System.exit(1);
 }
 semaphore.release();
 } catch (InterruptedException e) {
 System.out.println("信號量發生錯誤");
 e.printStackTrace();
 System.exit(1);
 }
 countDownLatch.countDown();
 });
 }
 countDownLatch.await();
 executorService.shutdown();
 System.out.println("所有執行緒格式化日期成功");
 }
}

此時,解決問題的關鍵代碼如下所示,

synchronized (simpleDateFormat){
simpleDateFormat.parse("2020-01-01");
}

運行程式,輸出結果如下所示,

所有執行緒格式化日期成功

需要注意的是,雖然這種方式能夠解決SimpleDateFormat類的執行緒安全問題,但是由于在程式的執行程序中,為SimpleDateFormat類物件加上了synchronized鎖,導致同一時刻只能有一個執行緒執行parse(String)方法,此時,會影響程式的執行性能,在要求高并發的生產環境下,此種方式也是不太推薦使用的,

3.Lock鎖方式

Lock鎖方式與synchronized鎖方式實作原理相同,都是在高并發下通過JVM的鎖機制來保證程式的執行緒安全,通過Lock鎖方式解決問題的代碼如下所示,

package io.binghe.concurrent.lab06;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
 * @author binghe
 * @version 1.0.0
 * @description 通過Lock鎖解決SimpleDateFormat類的執行緒安全問題
 */
public class SimpleDateFormatTest04 {
 //執行總次數
 private static final int EXECUTE_COUNT = 1000;
 //同時運行的執行緒數量
 private static final int THREAD_COUNT = 20;
 //SimpleDateFormat物件
 private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
 //Lock物件
 private static Lock lock = new ReentrantLock();
 public static void main(String[] args) throws InterruptedException {
 final Semaphore semaphore = new Semaphore(THREAD_COUNT);
 final CountDownLatch countDownLatch = new CountDownLatch(EXECUTE_COUNT);
 ExecutorService executorService = Executors.newCachedThreadPool();
 for (int i = 0; i < EXECUTE_COUNT; i++){
 executorService.execute(() -> {
 try {
 semaphore.acquire();
 try {
 lock.lock();
 simpleDateFormat.parse("2020-01-01");
 } catch (ParseException e) {
 System.out.println("執行緒:" + Thread.currentThread().getName() + " 格式化日期失敗");
 e.printStackTrace();
 System.exit(1);
 }catch (NumberFormatException e){
 System.out.println("執行緒:" + Thread.currentThread().getName() + " 格式化日期失敗");
 e.printStackTrace();
 System.exit(1);
 }finally {
 lock.unlock();
 }
 semaphore.release();
 } catch (InterruptedException e) {
 System.out.println("信號量發生錯誤");
 e.printStackTrace();
 System.exit(1);
 }
 countDownLatch.countDown();
 });
 }
 countDownLatch.await();
 executorService.shutdown();
 System.out.println("所有執行緒格式化日期成功");
 }
}

通過代碼可以得知,首先,定義了一個Lock型別的全域靜態變數作為加鎖和釋放鎖的句柄,然后在simpleDateFormat.parse(String)代碼之前通過lock.lock()加鎖,這里需要注意的一點是:為防止程式拋出例外而導致鎖不能被釋放,一定要將釋放鎖的操作放到finally代碼塊中,如下所示,

finally {
lock.unlock();
}

運行程式,輸出結果如下所示,

所有執行緒格式化日期成功

此種方式同樣會影響高并發場景下的性能,不太建議在高并發的生產環境使用,

4.ThreadLocal方式

使用ThreadLocal存盤每個執行緒擁有的SimpleDateFormat物件的副本,能夠有效的避免多執行緒造成的執行緒安全問題,使用ThreadLocal解決執行緒安全問題的代碼如下所示,

package io.binghe.concurrent.lab06;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
 * @author binghe
 * @version 1.0.0
 * @description 通過ThreadLocal解決SimpleDateFormat類的執行緒安全問題
 */
public class SimpleDateFormatTest05 {
 //執行總次數
 private static final int EXECUTE_COUNT = 1000;
 //同時運行的執行緒數量
 private static final int THREAD_COUNT = 20;
 private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>(){
 @Override
 protected DateFormat initialValue() {
 return new SimpleDateFormat("yyyy-MM-dd");
 }
 };
 public static void main(String[] args) throws InterruptedException {
 final Semaphore semaphore = new Semaphore(THREAD_COUNT);
 final CountDownLatch countDownLatch = new CountDownLatch(EXECUTE_COUNT);
 ExecutorService executorService = Executors.newCachedThreadPool();
 for (int i = 0; i < EXECUTE_COUNT; i++){
 executorService.execute(() -> {
 try {
 semaphore.acquire();
 try {
 threadLocal.get().parse("2020-01-01");
 } catch (ParseException e) {
 System.out.println("執行緒:" + Thread.currentThread().getName() + " 格式化日期失敗");
 e.printStackTrace();
 System.exit(1);
 }catch (NumberFormatException e){
 System.out.println("執行緒:" + Thread.currentThread().getName() + " 格式化日期失敗");
 e.printStackTrace();
 System.exit(1);
 }
 semaphore.release();
 } catch (InterruptedException e) {
 System.out.println("信號量發生錯誤");
 e.printStackTrace();
 System.exit(1);
 }
 countDownLatch.countDown();
 });
 }
 countDownLatch.await();
 executorService.shutdown();
 System.out.println("所有執行緒格式化日期成功");
 }
}

通過代碼可以得知,將每個執行緒使用的SimpleDateFormat副本保存在ThreadLocal中,各個執行緒在使用時互不干擾,從而解決了執行緒安全問題,

運行程式,輸出結果如下所示,

所有執行緒格式化日期成功

此種方式運行效率比較高,推薦在高并發業務場景的生產環境使用,

另外,使用ThreadLocal也可以寫成如下形式的代碼,效果是一樣的,

package io.binghe.concurrent.lab06;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
 * @author binghe
 * @version 1.0.0
 * @description 通過ThreadLocal解決SimpleDateFormat類的執行緒安全問題
 */
public class SimpleDateFormatTest06 {
 //執行總次數
 private static final int EXECUTE_COUNT = 1000;
 //同時運行的執行緒數量
 private static final int THREAD_COUNT = 20;
 private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>();
 private static DateFormat getDateFormat(){
 DateFormat dateFormat = threadLocal.get();
 if(dateFormat == null){
 dateFormat = new SimpleDateFormat("yyyy-MM-dd");
 threadLocal.set(dateFormat);
 }
 return dateFormat;
 }
 public static void main(String[] args) throws InterruptedException {
 final Semaphore semaphore = new Semaphore(THREAD_COUNT);
 final CountDownLatch countDownLatch = new CountDownLatch(EXECUTE_COUNT);
 ExecutorService executorService = Executors.newCachedThreadPool();
 for (int i = 0; i < EXECUTE_COUNT; i++){
 executorService.execute(() -> {
 try {
 semaphore.acquire();
 try {
 getDateFormat().parse("2020-01-01");
 } catch (ParseException e) {
 System.out.println("執行緒:" + Thread.currentThread().getName() + " 格式化日期失敗");
 e.printStackTrace();
 System.exit(1);
 }catch (NumberFormatException e){
 System.out.println("執行緒:" + Thread.currentThread().getName() + " 格式化日期失敗");
 e.printStackTrace();
 System.exit(1);
 }
 semaphore.release();
 } catch (InterruptedException e) {
 System.out.println("信號量發生錯誤");
 e.printStackTrace();
 System.exit(1);
 }
 countDownLatch.countDown();
 });
 }
 countDownLatch.await();
 executorService.shutdown();
 System.out.println("所有執行緒格式化日期成功");
 }
}

5.DateTimeFormatter方式

DateTimeFormatter是Java8提供的新的日期時間API中的類,DateTimeFormatter類是執行緒安全的,可以在高并發場景下直接使用DateTimeFormatter類來處理日期的格式化操作,代碼如下所示,

package io.binghe.concurrent.lab06;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
 * @author binghe
 * @version 1.0.0
 * @description 通過DateTimeFormatter類解決執行緒安全問題
 */
public class SimpleDateFormatTest07 {
 //執行總次數
 private static final int EXECUTE_COUNT = 1000;
 //同時運行的執行緒數量
 private static final int THREAD_COUNT = 20;
 private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
 public static void main(String[] args) throws InterruptedException {
 final Semaphore semaphore = new Semaphore(THREAD_COUNT);
 final CountDownLatch countDownLatch = new CountDownLatch(EXECUTE_COUNT);
 ExecutorService executorService = Executors.newCachedThreadPool();
 for (int i = 0; i < EXECUTE_COUNT; i++){
 executorService.execute(() -> {
 try {
 semaphore.acquire();
 try {
 LocalDate.parse("2020-01-01", formatter);
 }catch (Exception e){
 System.out.println("執行緒:" + Thread.currentThread().getName() + " 格式化日期失敗");
 e.printStackTrace();
 System.exit(1);
 }
 semaphore.release();
 } catch (InterruptedException e) {
 System.out.println("信號量發生錯誤");
 e.printStackTrace();
 System.exit(1);
 }
 countDownLatch.countDown();
 });
 }
 countDownLatch.await();
 executorService.shutdown();
 System.out.println("所有執行緒格式化日期成功");
 }
}

可以看到,DateTimeFormatter類是執行緒安全的,可以在高并發場景下直接使用DateTimeFormatter類來處理日期的格式化操作,

運行程式,輸出結果如下所示,

所有執行緒格式化日期成功

使用DateTimeFormatter類來處理日期的格式化操作運行效率比較高,推薦在高并發業務場景的生產環境使用,

6.joda-time方式

joda-time是第三方處理日期時間格式化的類別庫,是執行緒安全的,如果使用joda-time來處理日期和時間的格式化,則需要引入第三方類別庫,這里,以Maven為例,如下所示引入joda-time庫,

<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.9</version>
</dependency>

引入joda-time庫后,實作的程式代碼如下所示,

package io.binghe.concurrent.lab06;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
 * @author binghe
 * @version 1.0.0
 * @description 通過DateTimeFormatter類解決執行緒安全問題
 */
public class SimpleDateFormatTest08 {
 //執行總次數
 private static final int EXECUTE_COUNT = 1000;
 //同時運行的執行緒數量
 private static final int THREAD_COUNT = 20;
 private static DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
 public static void main(String[] args) throws InterruptedException {
 final Semaphore semaphore = new Semaphore(THREAD_COUNT);
 final CountDownLatch countDownLatch = new CountDownLatch(EXECUTE_COUNT);
 ExecutorService executorService = Executors.newCachedThreadPool();
 for (int i = 0; i < EXECUTE_COUNT; i++){
 executorService.execute(() -> {
 try {
 semaphore.acquire();
 try {
 DateTime.parse("2020-01-01", dateTimeFormatter).toDate();
 }catch (Exception e){
 System.out.println("執行緒:" + Thread.currentThread().getName() + " 格式化日期失敗");
 e.printStackTrace();
 System.exit(1);
 }
 semaphore.release();
 } catch (InterruptedException e) {
 System.out.println("信號量發生錯誤");
 e.printStackTrace();
 System.exit(1);
 }
 countDownLatch.countDown();
 });
 }
 countDownLatch.await();
 executorService.shutdown();
 System.out.println("所有執行緒格式化日期成功");
 }
}

這里,需要注意的是:DateTime類是org.joda.time包下的類,DateTimeFormat類和DateTimeFormatter類都是org.joda.time.format包下的類,如下所示,

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

運行程式,輸出結果如下所示,

所有執行緒格式化日期成功

使用joda-time庫來處理日期的格式化操作運行效率比較高,推薦在高并發業務場景的生產環境使用,

解決SimpleDateFormat類的執行緒安全問題的方案總結

綜上所示:在解決解決SimpleDateFormat類的執行緒安全問題的幾種方案中,區域變數法由于執行緒每次執行格式化時間時,都會創建SimpleDateFormat類的物件,這會導致創建大量的SimpleDateFormat物件,浪費運行空間和消耗服務器的性能,因為JVM創建和銷毀物件是要耗費性能的,所以,不推薦在高并發要求的生產環境使用,

synchronized鎖方式和Lock鎖方式在處理問題的本質上是一致的,通過加鎖的方式,使同一時刻只能有一個執行緒執行格式化日期和時間的操作,這種方式雖然減少了SimpleDateFormat物件的創建,但是由于同步鎖的存在,導致性能下降,所以,不推薦在高并發要求的生產環境使用,

ThreadLocal通過保存各個執行緒的SimpleDateFormat類物件的副本,使每個執行緒在運行時,各自使用自身系結的SimpleDateFormat物件,互不干擾,執行性能比較高,推薦在高并發的生產環境使用,

DateTimeFormatter是Java 8中提供的處理日期和時間的類,DateTimeFormatter類本身就是執行緒安全的,經壓測,DateTimeFormatter類處理日期和時間的性能效果還不錯(后文單獨寫一篇關于高并發下性能壓測的文章),所以,推薦在高并發場景下的生產環境使用,

joda-time是第三方處理日期和時間的類別庫,執行緒安全,性能經過高并發的考驗,推薦在高并發場景下的生產環境使用,

 

點擊關注,第一時間了解華為云新鮮技術~

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/554321.html

標籤:Java

上一篇:SpringBoot打包成WAR包的時候把第三方jar包打到LIB檔案夾下和把第三方jar包打入到SpringBoot jar包中

下一篇:返回列表

標籤雲
其他(160361) Python(38201) JavaScript(25475) Java(18189) C(15237) 區塊鏈(8269) C#(7972) AI(7469) 爪哇(7425) MySQL(7234) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5873) 数组(5741) R(5409) Linux(5346) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4582) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2434) ASP.NET(2403) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) .NET技术(1981) 功能(1967) HtmlCss(1952) Web開發(1951) C++(1929) python-3.x(1918) 弹簧靴(1913) xml(1889) PostgreSQL(1879) .NETCore(1863) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Simple Date Format類到底為啥不是執行緒安全的?

    摘要:我們就一起看下在高并發下Simple Date Format類為何會出現安全問題,以及如何解決Simple Date Format類的安全問題。 本文分享自華為云社區《【高并發】SimpleDateFormat類到底為啥不是執行緒安全的?》,作者:冰 河。 首先問下大家:你使用的Simple D ......

    uj5u.com 2023-06-06 07:45:11 more
  • SpringBoot打包成WAR包的時候把第三方jar包打到LIB檔案夾下和把

    ### SpringBoot打包成WAR包的時候把第三方jar包打到LIB檔案夾下和把第三方jar包打入到SpringBoot jar包中 [轉載](https://www.freesion.com/article/40631125428/) 1. 首先我們應該知道我們把`SPRINGBOOT`專案 ......

    uj5u.com 2023-06-06 07:45:02 more
  • 輕量靈動: 革新輕量級服務開發

    從 JDK 8 升級到 JDK 17 可以讓你的應用程式受益于新的功能、性能改進和安全增強。下面是一些 JDK 8 升級到 JDK 17 的最佳實戰 ......

    uj5u.com 2023-06-06 07:44:52 more
  • 演算法 in Go:Binary Search(二分查找)

    # 演算法 in Go:Binary Search(二分查找) ## Binary Search(二分查找) ### Binary Search(二分查找) - 猜數 - 1、2、3、4、5、6、7、8 - 排好序一個集合,先從中間開始猜,根據提示就可以排除一半,在剩余的一半里,再從中間開始猜,依此類 ......

    uj5u.com 2023-06-06 07:44:33 more
  • 從原始碼分析 Go 語言使用 cgo 導致的執行緒增長

    TDengine Go 連接器 使用 cgo 呼叫 taos.so 中的 API,使用程序中發現執行緒數不斷增長,本文從一個 cgo 呼叫開始決議 Go 原始碼,分析造成執行緒增長的原因。 ## 轉換 cgo 代碼 對 driver-go/wrapper/taosc.go 進行轉換 `go tool cg ......

    uj5u.com 2023-06-06 07:44:29 more
  • 驅動開發:內核實作SSDT掛鉤與摘鉤

    在前面的文章`《驅動開發:內核決議PE結構匯出表》`中我們封裝了兩個函式`KernelMapFile()`函式可用來讀取內核檔案,`GetAddressFromFunction()`函式可用來在匯出表中尋找指定函式的匯出地址,本章將以此為基礎實作對特定`SSDT`函式的`Hook`掛鉤操作,與`《驅... ......

    uj5u.com 2023-06-06 07:43:02 more
  • C++面試八股文:如何在堆上和堆疊上分配一塊記憶體?

    某日二師兄參加XXX科技公司的C++工程師開發崗位6面: > 面試官: 如何在堆上申請一塊記憶體? > > 二師兄:常用的方法有malloc,new等。 > > 面試官:兩者有什么區別? > > 二師兄:malloc是向作業系統申請一塊記憶體,這塊記憶體沒有經過初始化,通常需要使用memset手動初始化。 ......

    uj5u.com 2023-06-06 07:42:49 more
  • 驅動開發:內核實作SSDT掛鉤與摘鉤

    在前面的文章`《驅動開發:內核決議PE結構匯出表》`中我們封裝了兩個函式`KernelMapFile()`函式可用來讀取內核檔案,`GetAddressFromFunction()`函式可用來在匯出表中尋找指定函式的匯出地址,本章將以此為基礎實作對特定`SSDT`函式的`Hook`掛鉤操作,與`《驅... ......

    uj5u.com 2023-06-05 09:18:22 more
  • 6種限流方式

    服務限流,是指通過控制請求的速率或次數來達到保護服務的目的,在微服務中,我們通常會將它和熔斷、降級搭配在一起使用,來避免瞬時的大量請求對系統造成負荷,來達到保護服務平穩運行的目的。下面就來看一看常見的6種限流方式,以及它們的實作與使用。 ......

    uj5u.com 2023-06-05 09:07:09 more
  • 6種限流方式

    服務限流,是指通過控制請求的速率或次數來達到保護服務的目的,在微服務中,我們通常會將它和熔斷、降級搭配在一起使用,來避免瞬時的大量請求對系統造成負荷,來達到保護服務平穩運行的目的。下面就來看一看常見的6種限流方式,以及它們的實作與使用。 ......

    uj5u.com 2023-06-05 08:50:27 more