Skip to content

Instantly share code, notes, and snippets.

@mr-archano
Created May 22, 2015 13:10
Show Gist options
  • Save mr-archano/6929c2eb002c24eb9f8f to your computer and use it in GitHub Desktop.
Save mr-archano/6929c2eb002c24eb9f8f to your computer and use it in GitHub Desktop.
Thread safe SimpleDateFormat wrapper
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class SimpleDateFormatThreadSafe {
private final ThreadLocal<SimpleDateFormat> localSimpleDateFormat;
public SimpleDateFormatThreadSafe(final String pattern, final Locale locale, final TimeZone timeZone) {
localSimpleDateFormat = new ThreadLocal<SimpleDateFormat>() {
protected SimpleDateFormat initialValue() {
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern, locale);
dateFormat.setTimeZone(timeZone);
return dateFormat;
}
};
}
public String toString() {
return localSimpleDateFormat.get().toString();
}
public Date parse(String source) throws ParseException {
return localSimpleDateFormat.get().parse(source);
}
public Object clone() {
return localSimpleDateFormat.get().clone();
}
public int hashCode() {
return localSimpleDateFormat.get().hashCode();
}
public boolean equals(Object obj) {
return localSimpleDateFormat.get().equals(obj);
}
public String format(Date time) {
return localSimpleDateFormat.get().format(time);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment