2011-01-11 48 views

回答

12

如果有可能,請使用Joda Time。它的日期/時間解析器是線程安全的,並且它通常是比Date/Calendar更好的更多的

可以只使用它的解析器,然後將返回值轉換爲Date,但我個人建議使用整個庫。

1

爲什麼不把的SimpleDateFormat.parseObject()呼叫到自己的​​塊?

1

找到了solution

public class ThreadSafeSimpleDateFormat { 

private DateFormat df; 

public ThreadSafeSimpleDateFormat(String format) { 
    this.df = new SimpleDateFormat(format); 
} 

public synchronized String format(Date date) { 
    return df.format(date); 
} 

public synchronized Date parse(String string) throws ParseException { 
    return df.parse(string); 
} 
} 
+0

這可能無法正常使用,但它很容易。性能取決於有多少線程同時嘗試訪問格式化程序。我會試試這個(或者只是將您的調用包裝到SimpleDateFormat中的同步塊中),以查看它是否真的是一個問題。 – AngerClown 2011-01-11 14:31:17

8

this post中所述,您可以同步,使用線程本地或Joda-Time。

例如,使用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; 
    } 
} 
+1

+1沒有阻塞。用於線程安全的交易記憶。簡單情況下沒有外部大型圖書館。 – shellholic 2011-01-11 14:42:18