I want to make following code thread safe. What is the best way to achieve it?
private static final DateFormat DATE_FORMAT = DateFormat.getDateTimeInstance(
You can
Create a new DateFormat
instance every time you need one.
Use a synchronized
block, as pointed by @Giovanni Botta.
Use ThreadLocal
:
private static final ThreadLocal THREADLOCAL_FORMAT =
new ThreadLocal() {
@Override protected DateFormat initialValue() {
return DateFormat.getDateTimeInstance();
}
};
public static final String eventTypeToDateTimeString(long timestamp) {
return THREADLOCAL_FORMAT.get().format(new Date(timestamp));
}
Actually, using ThreadLocal
might give you the best performance if you have a thread pool (meaning threads are reused), which most web containers do.
http://www.javacodegeeks.com/2010/07/java-best-practices-dateformat-in.html