Friday, January 23, 2009

Formatter and new machines

Why is this code broken?

public class Stringifier {
    private final DateFormatter formatter = new SimpleDateFormatter("YYYMMDD");

    public String toYYYMMDD(final Date date) {
        return formatter.format(date);
    }
}

Here's the fixed code which makes the answer obvious:

public class Stringifier {
    private final DateFormatter formatter = new SimpleDateFormatter("YYYMMDD");

    public String toYYYMMDD(final Date date) {
        synchronized(formatter) {
            return formatter.format(date);
        }
    }
}

I checked recently and the lowest-powered servers my company buys have 8 cores. There is no such thing as single-threaded code. See the bug now?

Post a Comment