I have a number of Java date patterns and want to reuse them multiple times in SimpleDateFormat
objects across different threads, via static references, for speed.
The code would look something like this (inside a class called, say, FormatClass
):
private static String[] PATTERNS = new String[] {...};
public ThreadLocal<SimpleDateFormat[]> LOCAL_FORMATS = new ThreadLocal<SimpleDateFormat[]>
{
@Override
protected SimpleDateFormat[] initialValue()
{
List<SimpleDateFormat> formatList = new ArrayList<SimpleDateFormat>();
for (String pattern:PATTERNS)
{
formatList.add(new SimpleDateFormat(pattern);
}
return formatList.toArray(new SimpleDateFormat[0]);
}
}
Using the above code, a method on another class could format
(or parse
) multiple date strings as follows:
public static void printFormatted(String date)
{
for (SimpleDateFormat sdf:FormatClass.LOCAL_FORMATS.get())
{
System.out.println(sdf.format(date));
}
}
where the printFormatted()
method may or may not be static, but will definitely be accessed by multiple different threads.
Will the above approach work as expected?