同步访问 SimpleDateFormat [英] Synchronizing access to SimpleDateFormat

查看:24
本文介绍了同步访问 SimpleDateFormat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SimpleDateFormat 的 javadoc 声明 SimpleDateFormat 不同步.

The javadoc for SimpleDateFormat states that SimpleDateFormat is not synchronized.

"日期格式不同步.它建议单独创建为每个线程格式化实例.如果多线程访问一个格式同时,它必须是同步的外部."

"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 实例的最佳方法是什么?以下是我想到的几个选项,我过去曾使用过选项 1 和选项 2,但我很想知道是否有更好的替代方案,或者这些选项中哪一个可以提供最佳性能和并发性.

But what is the best approach to using an instance of SimpleDateFormat in a multi threaded environment. Here are a few options I have thought of, I have used options 1 and 2 in the past but I am curious to know if there are any better alternatives or which of these options would offer the best performance and concurrency.

选项 1:需要时创建本地实例

Option 1: Create local instances when required

public String formatDate(Date d) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    return sdf.format(d);
}

选项 2:创建 SimpleDateFormat 的实例作为类变量,但同步对其的访问.

Option 2: Create an instance of SimpleDateFormat as a class variable but synchronize access to it.

private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
public String formatDate(Date d) {
    synchronized(sdf) {
        return sdf.format(d);
    }
}

选项 3:创建一个 ThreadLocal 来为每个线程存储一个不同的 SimpleDateFormat 实例.

Option 3: Create a ThreadLocal to store a different instance of SimpleDateFormat for each thread.

private ThreadLocal<SimpleDateFormat> tl = new ThreadLocal<SimpleDateFormat>();
public String formatDate(Date d) {
    SimpleDateFormat sdf = tl.get();
    if(sdf == null) {
        sdf = new SimpleDateFormat("yyyy-MM-hh");
        tl.set(sdf);
    }
    return sdf.format(d);
}

推荐答案

  1. 创建 SimpleDateFormat 是 昂贵.除非很少使用,否则不要使用它.

  1. Creating SimpleDateFormat is expensive. Don't use this unless it's done seldom.

好的,如果你能忍受一点阻塞.如果 formatDate() 使用不多,请使用.

OK if you can live with a bit of blocking. Use if formatDate() is not used much.

如果您重用线程的最快选项(线程池).使用比 2 更多的内存.并且具有更高的启动开销.

Fastest option IF you reuse threads (thread pool). Uses more memory than 2. and has higher startup overhead.

对于应用程序,2. 和 3. 都是可行的选择.哪种最适合您的情况取决于您的用例.提防过早优化.仅当您认为这是一个问题时才这样做.

For applications both 2. and 3. are viable options. Which is best for your case depends on your use case. Beware of premature optimization. Only do it if you believe this is an issue.

对于第 3 方将使用的库,我会使用选项 3.

For libraries that would be used by 3rd party I'd use option 3.

这篇关于同步访问 SimpleDateFormat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆