Video in progress

Strong Middle 🧭 Design patterns

What is wrong with this Spring bean, and how does it show up under load?

@Service
public class StatementService {
    private final SimpleDateFormat fmt = new SimpleDateFormat("dd.MM.yyyy");
    private User currentUser;

    public String header(User user, Date from) {
        this.currentUser = user;
        return currentUser.getFullName() + " — " + fmt.format(from);
    }
}

In a singleton bean, mutable fields (SimpleDateFormat and currentUser) are shared by all threads. Under parallel requests, dates get formatted wrongly and one user may end up with another user's data.

📖 Answer

A Spring bean is a singleton by default, meaning one object is shared by all of Tomcat's worker threads. This class keeps state in a field.

With currentUser: thread A writes this.currentUser = alice, thread B immediately writes bob, and when A calls getFullName() it gets Bob's name. In a bank statement, that means another customer's data. It never shows up in a local test, because you send one request at a time.

SimpleDateFormat isn't thread-safe either: it has a Calendar field inside. Under load you get a NumberFormatException or simply wrong dates.

The fix:

@Service
public class StatementService {
    private static final DateTimeFormatter FMT = DateTimeFormatter.ofPattern("dd.MM.yyyy");

    public String header(User user, LocalDate from) {
        return user.getFullName() + " — " + FMT.format(from);
    }
}

DateTimeFormatter is immutable and thread-safe. The user comes in as a parameter and isn't stored in a field.

The rule is simple: a singleton bean should hold only final dependencies and immutable configuration. Anything request-specific goes in a parameter or, if needed, in request scope. In code review, when I see a write to a private field in a singleton, that's the first thing I ask about.