Java SimpleDateFormat 教学与错误用法

开发 Java 专案时经常操作时间、日期与字串的互相转换,最常见简单的方式是使用 SimpleDateFormat,想必大家对它不陌生。虽然它简单易用,如果没有正确使用,在一般环境下使用通常不会出错,但在高併发(Highly Concurrent)的环境下就可能会出现异常。

why-simple-date-format-is-bad.png

我们都知道在程式中应尽量少使用 new SimpleDateFormat,因为若频繁实例化,则需要花费较多的成本,因此我们尽可能共用同一个实例。假设有一个转换日期时间的 DateUtil 程式码如下

public class DateUtil {    private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");            public static String format(Date date) {        return simpleDateFormat.format(date);    }}

不幸的是,共用 SimpleDateFormat 就是最典型的错误用法。官方文件提到:

Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.

从 SimpleDateFormat 的原始码中也可以看到它是有状态的,而且其中 calendar 被宣告为成员变数,因此呼叫 format, parse 等 method 时会多次存取此 calendar。在高併发环境下,将会造成 race condition,结果值就会不符预期,甚至抛出 exception。

幸运的是,已有许多解决方案:

正确用法 1. 每次都 new

public class DateUtil {    public static String format(Date date) {        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");        return simpleDateFormat.format(date);    }}

这是最简单的做法,只要每次都宣告区域变数就可以了,区域变数是 thread-safe。若专案对于效能要求不高,也许可以考虑这个解法,或直到出现效能问题时再考虑其他方法。毕竟至少这个做法能正确运作,而且简单的作法往往是较好的。

正确用法 2. 加锁

public class DateUtil {    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");    synchronized public static String format(Date date) {        return simpleDateFormat.format(date);    }}

首先宣告 SimpleDateFormat field,避免重複 new 而造成效能问题。再加上关键字 synchronized 就能确保同一时刻只有一个 thread 能执行 format (mutual exclusion)。虽然这个方式不会出错,但可能降低併发度。

正确用法 3. 使用 ThreadLocal 容器

ThreadLocal 容器是一种让程式达到 thread-safety 的手段,它相当于给每个 thread 都开了一个独立的存储空间,既然 thread 之间互相隔离,自然解决了 race condition 的问题,也让 thread 能重複使用 SimpleDateFormat 实例。程式码如下:

public class DateUtil {    // 可以把 ThreadLocal<SimpleDateFormat> 视为一个全域 Map<Thread, SimpleDateFormat>,key 就是 current thread    // 意义上相当于 currentThread 专属、独立的 cache。    private static ThreadLocal<SimpleDateFormat> local = new ThreadLocal<>();    private static SimpleDateFormat getDateFormat() {        // currentThread 从自己的 ThreadLocalMap 取得 SimpleDateFormat。        // 如果是 null,则建立 SimpleDateFormat 并放入自己的 ThreadLocalMap 中。        SimpleDateFormat dateFormat = local.get();        if (dateFormat == null) {            dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");            local.set(dateFormat);        }        return dateFormat;    }    public static String format(Date date) {        return getDateFormat().format(date);    }}

举例来说,如果 thread pool 有 10 个 thread,程式就会建立 10 个 SimpleDateFormat 实例,这些 thread 们在每次的任务中重複使用各自的 SimpleDateFormat。但要注意一点,该 thread 能够重複被使用(例如 server 在处理完一次 request 后,thread 会再回到 thread pool 待命),否则效果会和方法1差不多。这个方法的缺点是程式会变得较複杂。

正确用法4. 改用 DateTimeFormatter(推荐)

虽然有点文不对题,毕竟这个问题困扰很多人许久了,因此在 Java 8 版本后官方就提供了 DateTimeFormatter 物件用来代替 SimpleDateFormat。就像官方文件中说的:

DateTimeFormatter in Java 8 is immutable and thread-safe alternative to SimpleDateFormat.

简单的範例如下:

将字串转成 LocalDate

String dateStr = "2022/05/24";DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");LocalDate date = LocalDate.parse(dateStr, formatter);

LocalDateTime 转成字串

LocalDateTime now = LocalDateTime.now();DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 hh:mm");System.out.println(now.format(formatter));

References

本文转录自我的部落格 https://kaisheng714.github.io/articles/simple-date-format

更多你可能会感兴趣的文章

常见的 Interface 错误用法多此一举! 不要这样用 Java 8 Optional

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章