SimpleDateFormat線程不安全的5種解決方案!


1.什么是線程不安全?

線程不安全也叫非線程安全,是指多線程執行中,程序的執行結果和預期的結果不符的情況就叫做線程不安全

線程不安全的代碼

SimpleDateFormat 就是一個典型的線程不安全事例,接下來我們動手來實現一下。首先我們先創建 10 個線程來格式化時間,時間格式化每次傳遞的待格式化時間都是不同的,所以程序如果正確執行將會打印 10 個不同的值,接下來我們來看具體的代碼實現:

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SimpleDateFormatExample {
    // 創建 SimpleDateFormat 對象
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");

    public static void main(String[] args) {
        // 創建線程池
        ExecutorService threadPool = Executors.newFixedThreadPool(10);
        // 執行 10 次時間格式化
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            // 線程池執行任務
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    // 創建時間對象
                    Date date = new Date(finalI * 1000);
                    // 執行時間格式化並打印結果
                    System.out.println(simpleDateFormat.format(date));
                }
            });
        }
    }
}

我們預期的正確結果是這樣的(10 次打印的值都不同):
image.png
然而,以上程序的運行結果卻是這樣的:
image.png
從上述結果可以看出,當在多線程中使用 SimpleDateFormat 進行時間格式化是線程不安全的。

2.解決方案

SimpleDateFormat 線程不安全的解決方案總共包含以下 5 種:

  1. SimpleDateFormat 定義為局部變量;
  2. 使用 synchronized 加鎖執行;
  3. 使用 Lock 加鎖執行(和解決方案 2 類似);
  4. 使用 ThreadLocal
  5. 使用 JDK 8 中提供的 DateTimeFormat

接下來我們分別來看每種解決方案的具體實現。

① 將SimpleDateFormat變為局部變量

SimpleDateFormat 定義為局部變量時,因為每個線程都是獨享 SimpleDateFormat 對象的,相當於將多線程程序變成“單線程”程序了,所以不會有線程不安全的問題,具體實現代碼如下:

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SimpleDateFormatExample {
    public static void main(String[] args) {
        // 創建線程池
        ExecutorService threadPool = Executors.newFixedThreadPool(10);
        // 執行 10 次時間格式化
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            // 線程池執行任務
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    // 創建 SimpleDateFormat 對象
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");
                    // 創建時間對象
                    Date date = new Date(finalI * 1000);
                    // 執行時間格式化並打印結果
                    System.out.println(simpleDateFormat.format(date));
                }
            });
        }
        // 任務執行完之后關閉線程池
        threadPool.shutdown();
    }
}

以上程序的執行結果為:
image.png
當打印的結果都不相同時,表示程序的執行是正確的,從上述結果可以看出,將 SimpleDateFormat 定義為局部變量之后,就可以成功的解決線程不安全問題了。

② 使用synchronized加鎖

鎖是解決線程不安全問題最常用的手段,接下來我們先用 synchronized 來加鎖進行時間格式化,實現代碼如下:

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SimpleDateFormatExample2 {
    // 創建 SimpleDateFormat 對象
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");

    public static void main(String[] args) {
        // 創建線程池
        ExecutorService threadPool = Executors.newFixedThreadPool(10);
        // 執行 10 次時間格式化
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            // 線程池執行任務
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    // 創建時間對象
                    Date date = new Date(finalI * 1000);
                    // 定義格式化的結果
                    String result = null;
                    synchronized (simpleDateFormat) {
                        // 時間格式化
                        result = simpleDateFormat.format(date);
                    }
                    // 打印結果
                    System.out.println(result);
                }
            });
        }
        // 任務執行完之后關閉線程池
        threadPool.shutdown();
    }
}

以上程序的執行結果為:
image.png

③ 使用Lock加鎖

在 Java 語言中,鎖的常用實現方式有兩種,除了 synchronized 之外,還可以使用手動鎖 Lock,接下來我們使用 Lock 來對線程不安全的代碼進行改造,實現代碼如下:

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Lock 解決線程不安全問題
 */
public class SimpleDateFormatExample3 {
    // 創建 SimpleDateFormat 對象
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");

    public static void main(String[] args) {
        // 創建線程池
        ExecutorService threadPool = Executors.newFixedThreadPool(10);
        // 創建 Lock 鎖
        Lock lock = new ReentrantLock();
        // 執行 10 次時間格式化
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            // 線程池執行任務
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    // 創建時間對象
                    Date date = new Date(finalI * 1000);
                    // 定義格式化的結果
                    String result = null;
                    // 加鎖
                    lock.lock();
                    try {
                        // 時間格式化
                        result = simpleDateFormat.format(date);
                    } finally {
                        // 釋放鎖
                        lock.unlock();
                    }
                    // 打印結果
                    System.out.println(result);
                }
            });
        }
        // 任務執行完之后關閉線程池
        threadPool.shutdown();
    }
}

以上程序的執行結果為:
image.png
從上述代碼可以看出,手動鎖的寫法相比於 synchronized 要繁瑣一些。

④ 使用ThreadLocal

加鎖方案雖然可以正確的解決線程不安全的問題,但同時也引入了新的問題,加鎖會讓程序進入排隊執行的流程,從而一定程度的降低了程序的執行效率,如下圖所示:
image.png
那有沒有一種方案既能解決線程不安全的問題,同時還可以避免排隊執行呢?

答案是有的,可以考慮使用 ThreadLocalThreadLocal 翻譯為中文是線程本地變量的意思,字如其人 ThreadLocal 就是用來創建線程的私有(本地)變量的,每個線程擁有自己的私有對象,這樣就可以避免線程不安全的問題了,實現如下:
image.png
知道了實現方案之后,接下來我們使用具體的代碼來演示一下 ThreadLocal 的使用,實現代碼如下:

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * ThreadLocal 解決線程不安全問題
 */
public class SimpleDateFormatExample4 {
    // 創建 ThreadLocal 對象,並設置默認值(new SimpleDateFormat)
    private static ThreadLocal<SimpleDateFormat> threadLocal =
            ThreadLocal.withInitial(() -> new SimpleDateFormat("mm:ss"));

    public static void main(String[] args) {
        // 創建線程池
        ExecutorService threadPool = Executors.newFixedThreadPool(10);
        // 執行 10 次時間格式化
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            // 線程池執行任務
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    // 創建時間對象
                    Date date = new Date(finalI * 1000);
                    // 格式化時間
                    String result = threadLocal.get().format(date);
                    // 打印結果
                    System.out.println(result);
                }
            });
        }
        // 任務執行完之后關閉線程池
        threadPool.shutdown();
    }
}

以上程序的執行結果為:
image.png

ThreadLocal和局部變量的區別

首先來說 ThreadLocal 不等於局部變量,這里的“局部變量”指的是像 2.1 示例代碼中的局部變量, ThreadLocal 和局部變量最大的區別在於:ThreadLocal 屬於線程的私有變量,如果使用的是線程池,那么 ThreadLocal 中的變量是可以重復使用的,而代碼級別的局部變量,每次執行時都會創建新的局部變量,二者區別如下圖所示:
image.png
更多關於 ThreadLocal 的內容,可以訪問磊哥前面的文章《ThreadLocal不好用?那是你沒用對!》

⑤ 使用DateTimeFormatter

以上 4 種解決方案都是因為 SimpleDateFormat 是線程不安全的,所以我們需要加鎖或者使用 ThreadLocal 來處理,然而,JDK 8 之后我們就有了新的選擇,如果使用的是 JDK 8+ 版本,就可以直接使用 JDK 8 中新增的、安全的時間格式化工具類 DateTimeFormatter 來格式化時間了,接下來我們來具體實現一下。

使用 DateTimeFormatter 必須要配合 JDK 8 中新增的時間對象 LocalDateTime 來使用,因此在操作之前,我們可以先將 Date 對象轉換成 LocalDateTime,然后再通過 DateTimeFormatter 來格式化時間,具體實現代碼如下:

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * DateTimeFormatter 解決線程不安全問題
 */
public class SimpleDateFormatExample5 {
    // 創建 DateTimeFormatter 對象
    private static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("mm:ss");

    public static void main(String[] args) {
        // 創建線程池
        ExecutorService threadPool = Executors.newFixedThreadPool(10);
        // 執行 10 次時間格式化
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            // 線程池執行任務
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    // 創建時間對象
                    Date date = new Date(finalI * 1000);
                    // 將 Date 轉換成 JDK 8 中的時間類型 LocalDateTime
                    LocalDateTime localDateTime =
                            LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
                    // 時間格式化
                    String result = dateTimeFormatter.format(localDateTime);
                    // 打印結果
                    System.out.println(result);
                }
            });
        }
        // 任務執行完之后關閉線程池
        threadPool.shutdown();
    }
}

以上程序的執行結果為:
image.png

3.線程不安全原因分析

要了解 SimpleDateFormat 為什么是線程不安全的?我們需要查看並分析 SimpleDateFormat 的源碼才行,那我們先從使用的方法 format 入手,源碼如下:

private StringBuffer format(Date date, StringBuffer toAppendTo,
                                FieldDelegate delegate) {
    // 注意此行代碼
    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;
}

也許是好運使然,沒想到剛開始分析第一個方法就找到了線程不安全的問題所在。

從上述源碼可以看出,在執行 SimpleDateFormat.format 方法時,會使用 calendar.setTime 方法將輸入的時間進行轉換,那么我們想象一下這樣的場景:

  1. 線程 1 執行了 calendar.setTime(date) 方法,將用戶輸入的時間轉換成了后面格式化時所需要的時間;
  2. 線程 1 暫停執行,線程 2 得到 CPU 時間片開始執行;
  3. 線程 2 執行了 calendar.setTime(date) 方法,對時間進行了修改;
  4. 線程 2 暫停執行,線程 1 得出 CPU 時間片繼續執行,因為線程 1 和線程 2 使用的是同一對象,而時間已經被線程 2 修改了,所以此時當線程 1 繼續執行的時候就會出現線程安全的問題了。

正常的情況下,程序的執行是這樣的:
image.png

非線程安全的執行流程是這樣的:
image.png
在多線程執行的情況下,線程 1 的 date1 和線程 2 的 date2,因為執行順序的問題,最終都被格式化成 date2 formatted,而非線程 1 date1 formatted 和線程 2 date2 formatted,這樣就會導致線程不安全的問題。

4.各方案優缺點總結

如果使用的是 JDK 8+ 版本,可以直接使用線程安全的 DateTimeFormatter 來進行時間格式化,如果使用的 JDK 8 以下版本或者改造老的 SimpleDateFormat 代碼,可以考慮使用 synchronizedThreadLocal 來解決線程不安全的問題。因為實現方案 1 局部變量的解決方案,每次執行的時候都會創建新的對象,因此不推薦使用。synchronized 的實現比較簡單,而使用 ThreadLocal 可以避免加鎖排隊執行的問題。

關注公號「Java中文社群」查看更多有意思、漲知識的並發編程文章。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM