Singleton Bean
Concurrent Requests
Java Beans
Multithreading
Java EE

How does the singleton Bean serve the concurrent request?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

A singleton bean is a single shared object instance, not a single-threaded object. In a web application, many request threads can call methods on that same bean at the same time, so the real question is not how the bean serves concurrency, but whether the code inside the bean is safe under concurrent access.

What Singleton Scope Actually Means

In frameworks such as Spring, singleton scope usually means one bean instance per application context. The container creates the object once and reuses it for every component that depends on it.

When HTTP requests arrive, the web container assigns each request to a worker thread. If twenty users hit the same endpoint, twenty threads may enter the same singleton service concurrently.

java
1import java.math.BigDecimal;
2import org.springframework.stereotype.Service;
3
4@Service
5public class PricingService {
6    public BigDecimal calculateTotal(BigDecimal subtotal, BigDecimal taxRate) {
7        return subtotal.add(subtotal.multiply(taxRate));
8    }
9}

This service is safe because it is stateless. Every value needed for the calculation comes in as a method parameter, and the method uses only local variables.

Why Stateless Beans Work Well

Local variables belong to the executing thread's stack, not to shared object state. That means one request cannot overwrite another request's temporary values when the bean is designed as a stateless service.

This is why singleton scope is the default for many service classes. It avoids repeated object creation and works well as long as the bean does not keep mutable request-specific data in fields.

A second example shows the same pattern:

java
1import java.time.Instant;
2import java.util.UUID;
3import org.springframework.stereotype.Service;
4
5@Service
6public class AuditService {
7    public String createEventId(String userId) {
8        return userId + "-" + Instant.now().toEpochMilli() + "-" + UUID.randomUUID();
9    }
10}

Even with many concurrent requests, each invocation builds its result independently.

Where Concurrency Problems Begin

Trouble starts when a singleton bean stores mutable state in instance fields. Those fields are shared across all threads.

java
1import org.springframework.stereotype.Service;
2
3@Service
4public class UnsafeCounterService {
5    private long counter = 0;
6
7    public long nextValue() {
8        counter++;
9        return counter;
10    }
11}

counter++ is not atomic. Two threads can read the same value, increment it, and both write back the same result. That causes lost updates.

A safer implementation uses an atomic type.

java
1import java.util.concurrent.atomic.AtomicLong;
2import org.springframework.stereotype.Service;
3
4@Service
5public class SafeCounterService {
6    private final AtomicLong counter = new AtomicLong();
7
8    public long nextValue() {
9        return counter.incrementAndGet();
10    }
11}

If the bean truly needs shared mutable state, you need thread-safe structures, locking, atomic classes, or an external store.

Spring Singleton Versus EJB Singleton

The word singleton appears in multiple Java ecosystems, but the concurrency model differs.

In Spring, singleton scope mostly describes lifecycle and sharing. The framework does not make your bean thread-safe for you.

In EJB, @Singleton beans can use container-managed concurrency rules. You can mark methods as read or write operations and let the container coordinate access.

java
1import jakarta.ejb.Lock;
2import jakarta.ejb.LockType;
3import jakarta.ejb.Singleton;
4import java.util.HashMap;
5import java.util.Map;
6
7@Singleton
8public class ConfigCache {
9    private final Map<String, String> values = new HashMap<>();
10
11    @Lock(LockType.READ)
12    public String get(String key) {
13        return values.get(key);
14    }
15
16    @Lock(LockType.WRITE)
17    public void put(String key, String value) {
18        values.put(key, value);
19    }
20}

That model is useful when shared in-memory state is intentional and controlled.

Choosing a Better Scope for Request Data

If data belongs to one request, it usually should not live in a singleton field at all. In Spring, request-scoped components are a better place for per-request state.

java
1import org.springframework.stereotype.Component;
2import org.springframework.web.context.annotation.RequestScope;
3
4@Component
5@RequestScope
6public class RequestMetadata {
7    private String correlationId;
8
9    public String getCorrelationId() {
10        return correlationId;
11    }
12
13    public void setCorrelationId(String correlationId) {
14        this.correlationId = correlationId;
15    }
16}

The singleton service can still orchestrate work, but request-specific values stay isolated.

Practical Rule of Thumb

If a singleton bean only reads collaborators, uses method parameters, and creates local variables, it is usually safe. If it mutates shared fields, assume you have a concurrency problem until you prove otherwise.

That rule explains why most service beans work fine under load while a small number of cache-like or counter-like beans create difficult race conditions.

Common Pitfalls

A common misconception is believing that one singleton instance means one request at a time. It does not. Multiple threads may enter the same bean concurrently.

Another mistake is storing request data in instance fields for convenience. That can leak values across users and create nondeterministic bugs.

Developers also sometimes add synchronized everywhere without measuring the cost. That may fix correctness but create a throughput bottleneck if the bean is hot.

Finally, some shared state simply belongs somewhere else. If the data must survive restarts or be shared across multiple application nodes, a database or distributed cache is often the better choice.

Summary

  • Singleton scope means one shared instance, not serialized access.
  • Many request threads can call the same singleton bean at once.
  • Stateless singleton beans are usually safe and are the normal design.
  • Mutable instance fields require explicit thread-safety measures.
  • Put request-specific data in request scope instead of singleton fields.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.