Heya!
I'm using joda due to it's good reputation regarding multi threading. It goes great distances to make multi threaded date handling efficient, for example by making all Date/Time/DateTime objects immutable.
But here's a situation where I'm not sure if Joda is really doing the right thing. It probably does, but I'm very interested to see an explanation.
When a toString() of a DateTime is being called Joda does the following:
/* org.joda.time.base.AbstractInstant */
public String toString() {
return ISODateTimeFormat.dateTime().print(this);
}
All formatters are thread safe (they immutable as well), but what's about the formatter-factory:
private static DateTimeFormatter dt;
/* org.joda.time.format.ISODateTimeFormat */
public static DateTimeFormatter dateTime() {
if (dt == null) {
dt = new DateTimeFormatterBuilder()
.append(date())
.append(tTime())
.toFormatter();
}
return dt;
}
This is a common pattern in single threaded applications but it is known to be error-prone in a multithreaded environment.
I see the following dangers:
- Race condition during null check --> worst case: two objects get created.
No Problem, as this is solely a helper object (unlike a normal singleton pattern situation), one gets saved in dt, the other is lost and will be garbage collected sooner or later.
- the static variable might point to a partially constructed object before the objec has been finished initialization
(before calling me crazy, read about a similar situation in this Wikipedia article.)
So how does Joda ensure that no partially created formatter gets published in this static variable?
Thanks for your explanations!
Reto