运用ThreadLocal保证DateFormat线程安全

使用ThreadLocal保证DateFormat线程安全大家都知道DateFormat是线程非安全的, 一般在多线程环境下, 必须为

使用ThreadLocal保证DateFormat线程安全
大家都知道DateFormat是线程非安全的, 一般在多线程环境下, 必须为每一次日期时间的转换创建一个DateFormat, 这里有一个更高效的做法:

package com.javacodegeeks.test;import java.text.DateFormat;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;public class ConcurrentDateFormatAccess { private ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat> () {  @Override  public DateFormat get() {   return super.get();  }  @Override  protected DateFormat initialValue() {   return new SimpleDateFormat("yyyy MM dd");  }  @Override  public void remove() {   super.remove();  }  @Override  public void set(DateFormat value) {   super.set(value);  } }; public Date convertStringToDate(String dateString) throws ParseException {  return df.get().parse(dateString); }}

1 楼 黑猪王子 2012-04-06   貌似这种方法是通用的   用ThreadLocal解决线程安全问题