← 中文资源

简体中文版本

SimpleDateFormat 非线程安全

javadoc 明言日期格式对象不同步:并发共享会产出错值或异常。按次新建实例可免加锁,DateTimeFormatter 不可变、可安全共享为常量。

阅读英文原文

实现说明

全部逻辑都在类 SharedDateFormat和函数 safePerCall、main中。

使用要点

  • main 按顺序串起 safePerCall;运行文件就会把这个流程跑一遍。

常见问题

「SimpleDateFormat 非线程安全」这个示例怎么运行?

运行这个文件就行;脚本没有任何外部要求。

主要签名是 static String safePerCall(Instant instant)

核心语句

return fmt.format(Date.from(instant));

代码示例

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.TimeZone;

public class SharedDateFormat {

    // SimpleDateFormat javadoc: "Date formats are not synchronized. It is
    // recommended to create separate format instances for each thread."
    static final String PATTERN = "yyyy-MM-dd HH:mm:ss";

    // 每次调用新建实例:不跨线程共享,无需外部同步
    static String safePerCall(Instant instant) {
        SimpleDateFormat fmt = new SimpleDateFormat(PATTERN);
        fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
        return fmt.format(Date.from(instant));
    }

    public static void main(String[] args) {
        Instant instant = Instant.parse("2023-11-14T22:13:20Z");

        System.out.println(safePerCall(instant));

        // DateTimeFormatter 不可变:javadoc 建议它作为 immutable、thread-safe 的替代
        DateTimeFormatter shared = DateTimeFormatter.ofPattern(PATTERN).withZone(ZoneOffset.UTC);
        System.out.println(shared.format(instant));
    }
}