Is this is a right way to make java.text.DateFormat threadSafe?

I'm working on a project where the date format is kept as a static Utility field as shown below

public static final SimpleDateFormat MM_DD_YYYY = new SimpleDateFormat(DATE_FORMAT_DEFAULT, Locale.US);

Luckily FindBugs started giving the warning that the DateFormats are inherently unsafe for multithreaded use.

To remove these warnings one of the developer in the team changed the field access to private and provided a public accessor function like this

private static final SimpleDateFormat MM_DD_YYYY = new SimpleDateFormat(DATE_FORMAT_DEFAULT, Locale.US);
public static SimpleDateFormat getMmDdYyyy() {
    return MM_DD_YYYY;
}

Magically FindBugs warnings disappeared! My question is Doesn't the both snippets of code are semantically same?

If yes Why not the Findbugs showing any warnings in the second case?

Jon Skeet
people
quotationmark

Well it's better in that having public fields is almost always a bad idea, particularly for mutable objects.

However, it's definitely still not thread-safe. Two threads could absolutely call the method and end up using the formatter at the same time.

You could create your own wrapper object (possibly still extending DateFormat; I'm not sure offhand) which serialized requests and possibly had a "pool" of underlying formats. Or you could use Joda Time or java.time, both of which are much better date/time APIs to start with, and have thread-safe formatters.

Another alternative would be to just have two static methods, parseMonthDayYear and formatMonthDayYear, and let them take care of thread safety.

people

See more on this question at Stackoverflow