I want to make following code thread safe. What is the best way to achieve it?
private static final DateFormat DATE_FORMAT = DateFormat.getDateTimeInstance();
public static final String eventTypeToDateTimeString(long timestamp)
{
return DATE_FORMAT.format(new Date(timestamp));
}
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<DateFormat> THREADLOCAL_FORMAT =
new ThreadLocal<DateFormat>() {
@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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With