多线程环境下使用 DateFormat

作者: Java及SpringBoot | 来源:发表于2018-05-22 10:11 被阅读23次

DateFormat 类是一个非线程安全的类。javadocs 文档里面提到"Date formats是不能同步的。 我们建议为每个线程创建独立的日期格式。 如果多个线程同时访问一个日期格式,这需要在外部加上同步代码块。"

如何并发使用DateFormat类

1. 同步

最简单的方法就是在做日期转换之前,为DateFormat对象加锁。这种方法使得一次只能让一个线程访问DateFormat对象,而其他线程只能等待。

private final DateFormat format = new SimpleDateFormat("yyyyMMdd");

public Date convert(String source) throws ParseException {
    synchronized (format) {
        Date d = format.parse(source);
        return d;
    }
}

2.使用ThreadLocal

另外一个方法就是使用ThreadLocal变量去容纳DateFormat对象,也就是说每个线程都有一个属于自己的副本,并无需等待其他线程去释放它。这种方法会比使用同步块更高效。

private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>() {
    @Override
    protected DateFormat initialValue() {
        return new SimpleDateFormat("yyyyMMdd");
    }
};

public Date convert(String source) throws ParseException {
    Date d = df.get().parse(source);
    return d;
}

3.Joda-Time

Joda-Time 是一个很棒的开源的 JDK 的日期和日历 API 的替代品,其 DateTimeFormat 是线程安全而且不变的。

private final DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyyMMdd");

public Date convert(String source) {
    DateTime d = fmt.parseDateTime(source);
    return d.toDate();
}

4.Apache commons-lang中的FastDateFormat

private String initDate() {
    Date d = new Date();
    FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");
    return fdf.format(d);
}

相关文章

  • 多线程环境下使用 DateFormat

    DateFormat 类是一个非线程安全的类。javadocs 文档里面提到"Date formats是不能同步的...

  • SimpleDateFormat安全性问题

    demo演示 我们都知道DateFormat和SimpleDateFormat都是非线程安全的类,在多线程环境下并...

  • 2018-12-11

    10. HashMap在多线程环境下使用需要注意什么?为什么? 在多线程环境下,需要使用ConcurrentHas...

  • 时间处理

    多线程使用DateFormat [Joda-Time] 是一个很棒的开源的 JDK 的日期和日历 API 的替代品...

  • 多线程编程

    多线程编程之Linux环境下的多线程(一)多线程编程之Linux环境下的多线程(二)多线程编程之Linux环境下的...

  • Seckill秒杀分布式锁使用

    controller service dao 使用jmeter jmeter使用教程 输出 结论 多线程环境下超卖...

  • multiple-thread Note

    在多线程环境下,注意确认使用的方法是否是线程安全的方法!

  • ConcurrentHashMap

    为神什么要使用ConcurrentHashMap?hashMap线程不安全在多线程环境下,使用HashMap进行p...

  • VUE Element 时间戳转换时间

    //使用:formatter="dateFormat"绑定一个dateFormat方法 首先要先在你的项目中下载 ...

  • java并发容器-ConcurrentHashMap-大概了解

    在多线程环境下,HashMap不符合使用场景,因为不是线程安全的,而如果使用Collections.synchro...

网友评论

    本文标题:多线程环境下使用 DateFormat

    本文链接:https://www.haomeiwen.com/subject/krfhjftx.html