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

查看:104
本文介绍了同步对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来存储不同的实例

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是昂贵的

如果你可以忍受一点阻塞,那么不要使用它。

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

如果您重复使用线程,最快的选项(线程池)。

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。

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

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

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