Reputation: 111
I have a requirement to convert incoming date string format "20130212" (YYYYMMDD) to 12/02/2013 (DD/MM/YYYY)
using ThreadLocal
. I know a way to do this without the ThreadLocal
. Can anyone help me?
Conversion without ThreadLocal
:
final SimpleDateFormat format2 = new SimpleDateFormat("MM/dd/yyyy");
final SimpleDateFormat format1 = new SimpleDateFormat("yyyyMMdd");
final Date date = format1.parse(tradeDate);
final Date formattedDate = format2.parse(format2.format(date));
Upvotes: 10
Views: 16264
Reputation: 79015
The modern Date-Time classes introduced with Java-8 are thread-safe.
Demo:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
DateTimeFormatter parser = DateTimeFormatter.ofPattern("uuuuMMdd", Locale.ENGLISH);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/uuuu", Locale.ENGLISH);
LocalDate date = LocalDate.parse("20130212", parser);
String formattedString = date.format(formatter);
System.out.println(formattedString);
}
}
Output:
12/02/2013
Note that I prefer u to y with DateTimeFormatter
.
Learn more about the modern Date-Time API from Trail: Date Time.
Upvotes: 1
Reputation: 9266
ThreadLocal in Java is a way to achieve thread-safety apart from writing immutable classes. Since SimpleDateFormat is not thread safe, you can use a ThreadLocal to make it thread safe.
class DateFormatter{
private static ThreadLocal<SimpleDateFormat> outDateFormatHolder = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("MM/dd/yyyy");
}
};
private static ThreadLocal<SimpleDateFormat> inDateFormatHolder = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyyMMdd");
}
};
public static String formatDate(String date) throws ParseException {
return outDateFormatHolder.get().format(
inDateFormatHolder.get().parse(date));
}
}
Upvotes: 11
Reputation: 135992
The idea behind this is that SimpleDateFormat is not thread-safe so in a mutil-threaded app you cannot share an instance of SimpleDateFormat between multiple threads. But since creation of SimpleDateFormat is an expensive operation we can use a ThreadLocal as workaround
static ThreadLocal<SimpleDateFormat> format1 = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd");
}
};
public String formatDate(Date date) {
return format1.get().format(date);
}
Upvotes: 15