线程安全日期解析器

sbl*_*ndy 10 java date thread-safety

我正在寻找一个线程安全的替代品SimpleDateFormat.parseObject好旧FastDateFormat没有实现,只是抛出一个错误.有任何想法吗?我不需要任何花哨的东西,只需要线程安全性和处理这种模式的能力:"yyyy-MM-dd".

Jon*_*eet 13

如果可能的话,使用Joda Time.它的日期/时间解析器是线程安全的,它通常是一个很多比更好的API Date/ Calendar.

可以只使用它的解析器,然后将返回值转换为Date,但我个人建议使用整个库.


dog*_*ane 8

作为概括这篇文章你可以同步使用线程局部变量或乔达时间.

例如,使用ThreadLocals:

public class DateFormatTest {

  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;
  }
}
Run Code Online (Sandbox Code Playgroud)