同步对 SimpleDateFormat 的访问

SimpleDateFormat 的 javadoc 指出 SimpleDateFormat 没有同步。

”日期格式不同步 建议创建独立的 格式化每个线程的实例 多线程访问一种格式 同时,它必须是同步的 对外。”

但是在多线程环境中使用 SimpleDateFormat 实例的最佳方法是什么呢。下面是我想到的一些选项,我过去使用过选项1和选项2,但我很好奇是否有更好的选项,或者这些选项中哪一个能提供最佳的性能和并发性。

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

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

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

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

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

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);
}
23476 次浏览
  1. Creating SimpleDateFormat is expensive. Don't use this unless it's done seldom.

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

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

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.

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

Don't use SimpleDateFormat, use joda-time's DateTimeFormatter instead. It is a bit stricter in the parsing side and so isn't quite a drop in replacement for SimpleDateFormat, but joda-time is much more concurrent friendly in terms of safety and performance.

The other option is Commons Lang FastDateFormat but you can only use it for date formatting and not parsing.

Unlike Joda, it can function as a drop-in replacement for formatting. (Update: Since v3.3.2, FastDateFormat can produce a FastDateParser, which is a drop-in thread-safe replacement for SimpleDateFormat)

I would say, create a simple wrapper-class for SimpleDateFormat that synchronizes access to parse() and format() and can be used as a drop-in replacement. More foolproof than your option #2, less cumbersome than your option #3.

Seems like making SimpleDateFormat unsynchronized was a poor design decision on the part of the Java API designers; I doubt anyone expects format() and parse() to need to be synchronized.

Imagine your application has one thread. Why would you synchronize access to SimpleDataFormat variable then?

Commons Lang 3.x now has FastDateParser as well as FastDateFormat. It is thread safe and faster than SimpleDateFormat. It also uses the same format/parse pattern specifications as SimpleDateFormat.

Another option is to keep instances in a thread-safe queue:

import java.util.concurrent.ArrayBlockingQueue;
private static final int DATE_FORMAT_QUEUE_LEN = 4;
private static final String DATE_PATTERN = "yyyy-MM-dd HH:mm:ss";
private ArrayBlockingQueue<SimpleDateFormat> dateFormatQueue = new ArrayBlockingQueue<SimpleDateFormat>(DATE_FORMAT_QUEUE_LEN);
// thread-safe date time formatting
public String format(Date date) {
SimpleDateFormat fmt = dateFormatQueue.poll();
if (fmt == null) {
fmt = new SimpleDateFormat(DATE_PATTERN);
}
String text = fmt.format(date);
dateFormatQueue.offer(fmt);
return text;
}
public Date parse(String text) throws ParseException {
SimpleDateFormat fmt = dateFormatQueue.poll();
if (fmt == null) {
fmt = new SimpleDateFormat(DATE_PATTERN);
}
Date date = null;
try {
date = fmt.parse(text);
} finally {
dateFormatQueue.offer(fmt);
}
return date;
}

The size of dateFormatQueue should be something close to the estimated number of threads which can routinely call this function at the same time. In the worst case where more threads than this number do actually use all the instances concurrently, some SimpleDateFormat instances will be created which cannot be returned to dateFormatQueue because it is full. This will not generate an error, it will just incur the penalty of creating some SimpleDateFormat which are used only once.

If you are using Java 8, you may want to use java.time.format.DateTimeFormatter:

This class is immutable and thread-safe.

e.g.:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String str = new java.util.Date().toInstant()
.atZone(ZoneId.systemDefault())
.format(formatter);

I just implemented this with Option 3, but made a few code changes:

  • ThreadLocal should usually be static
  • Seems cleaner to override initialValue() rather than test if (get() == null)
  • You may want to set locale and time zone unless you really want the default settings (defaults are very error prone with Java)

    private static final ThreadLocal<SimpleDateFormat> tl = new ThreadLocal<SimpleDateFormat>() {
    @Override
    protected SimpleDateFormat initialValue() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-hh", Locale.US);
    sdf.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
    return sdf;
    }
    };
    public String formatDate(Date d) {
    return tl.get().format(d);
    }