Partially constructed object / Multi threading
- by reto
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 is correct, but I'd be very interested to see the explanation for it.
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, as they are as well ready-only. 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. 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 not partially created formatter gets published in this static variable?
Thanks for your explanations!
Reto