Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Because DateFormat is not thread-safe [API 2011], the value for Date returned by the parse() method might fail to correspond to the str argument:

...

This compliant solution creates and returns a new DateFormat instance for each invocation of the parse() method [API 2011]:

Code Block
bgColor#ccccff
final class DateHandler {
  public static java.util.Date parse(String str) throws ParseException {
    return DateFormat.getDateInstance(DateFormat.MEDIUM).parse(str);
  }
}

...

This compliant solution makes DateHandler thread-safe by synchronizing statements within the parse() method [API 2011]:

Code Block
bgColor#ccccff
final class DateHandler {
  private static DateFormat format =
    DateFormat.getDateInstance(DateFormat.MEDIUM);

  public static java.util.Date parse(String str) throws ParseException {
    synchronized (format) {
      return format.parse(str);
    }
  }
}

...

Technically, strict immutability of the referent is a stronger condition than is fundamentally required for safe publication. When it can be determined that a referent is thread-safe by design, the field that holds its reference may be declared volatile. However, this approach to using volatile decreases maintainability and should be avoided.

Bibliography

[API 2011]

Class DateFormat

[Goetz 2007]

Pattern 2, "One-Time Safe Publication"

[JLS 2011]

§8.3.1.4, "volatile Fields"

[Miller 2009]

"Mutable Statics"

...