On this page
- 1. · Concept & Definition
- 2. · Why It Matters
- 3. · How It Works
- Deep Dive — Lock Semantics, Start-up Failures and the CDI Equivalent
- 4. · Java / Jakarta EE Code Examples
- 5. · Configuration, Defaults & Diagnostics
- 6. · Production Usage Patterns
- 7. · Common Pitfalls & Misconceptions
- 8. · Best Practices
- 9. · Architect's Perspective & Trade-offs
- 10. · Interview Q&A
1· Concept & Definition
A singleton session bean (@Singleton, jakarta.ejb) is instantiated once per application (per JVM in a cluster) and shared by all clients. It supports eager initialisation at startup, ordering between singletons, and container-managed concurrency with read/write locks.

2· Why It Matters
- Standard place for application-wide state such as caches, configuration and coordination.
- Startup singletons run initialisation logic before the application serves traffic.
- Default write locking can silently serialise all calls and become a bottleneck.
Most applications need a little state that genuinely belongs to the whole application: reference data loaded once, a registry of connected clients, a rate limiter, a coordinator for background work. Before singletons were standardised in EJB 3.1, teams improvised with static fields, which the container could not manage, or with stateless beans holding shared caches, which created one copy per pooled instance. The singleton gives that state a defined home with container-managed lifecycle, start-up ordering and locking. Its weakness is the default: every method is write-locked, so a bean called on every request can quietly turn a multi-threaded server into a single queue. Knowing that default is the difference between a cache and a bottleneck.
3· How It Works
Application state
Instance fields of a singleton hold state shared by the whole application: reference data caches, counters, configuration, registries. In a cluster, each node has its own singleton — cluster-wide singletons require vendor features or external coordination.
Initialization
| Annotation | Effect |
|---|---|
@Startup | Instantiate during application startup (otherwise on first use) |
@DependsOn("OtherSingleton") | Initialise after the named singletons (and destroy before them) |
@PostConstruct | Initialisation logic; exceptions prevent the singleton (and possibly deployment) |
@PreDestroy | Cleanup at shutdown |
@PostConstruct of a singleton runs in a transaction context according to its transaction attribute (REQUIRED by default for CMT), so startup initialisation can read from the database.
Concurrency
| Mechanism | Behaviour |
|---|---|
| Container-managed (default) | Every method has a lock type; default @Lock(WRITE) = exclusive |
@Lock(LockType.READ) | Concurrent access with other READ methods |
@AccessTimeout | Maximum wait for a lock; ConcurrentAccessTimeoutException when exceeded (0 = no wait, −1 = wait indefinitely) |
@ConcurrencyManagement(BEAN) | No container locking; developer synchronises |

Deep Dive — Lock Semantics, Start-up Failures and the CDI Equivalent
Container-managed concurrency is a read/write lock per singleton instance, acquired by the container's proxy before the method body runs and released when it returns. Any number of READ methods can run together; a WRITE method waits until current readers have finished and then excludes everyone else. Two details cause production incidents. The lock is held for the whole method, including any remote call or query inside it, so a slow dependency under a WRITE lock stalls every caller of the bean. And a READ method that calls a WRITE method of the same bean through its business object is asking for a lock upgrade, which the specification forbids: the container throws IllegalLoopbackException. A plain call on this takes no lock at all.
Start-up has its own traps. An exception from the @PostConstruct of a @Startup singleton aborts the deployment on most servers, which is right for mandatory configuration but wrong for an optional cache warm-up that should degrade gracefully, so catch and log in that case. And because every cluster node runs its own instance, an @Schedule timer on a singleton fires once per node; a nightly job that must run exactly once needs a clustered persistent timer, a database lock row or a Kubernetes CronJob.
For new code the same behaviour is easy to express with CDI and Jakarta Concurrency, with the concurrency made explicit: an immutable snapshot swapped atomically gives lock-free reads, and a managed scheduled executor keeps the refresh on a container thread with context.
// static imports: TimeUnit.MINUTES, System.Logger.Level.WARNING
@ApplicationScoped
public class ExchangeRates {
private static final System.Logger LOG =
System.getLogger(ExchangeRates.class.getName());
@Inject RateClient client;
@Resource ManagedScheduledExecutorService scheduler;
private final AtomicReference<Map<String, BigDecimal>> rates =
new AtomicReference<>(Map.of());
void onStart(@Observes Startup event) { // eager, like @Startup
refresh();
scheduler.scheduleAtFixedRate(this::refresh, 10, 10, MINUTES);
}
public BigDecimal rate(String ccy) { // lock-free read
return rates.get().get(ccy);
}
void refresh() {
try {
rates.set(Map.copyOf(client.fetchAll())); // build, swap
} catch (RuntimeException e) {
LOG.log(WARNING, "rate refresh failed; keeping snapshot", e);
}
}
}The try/catch inside refresh matters: a periodic task that throws is silently cancelled by the executor, so without it one failed fetch would freeze the cache at its last good value with no further attempts.
4· Java / Jakarta EE Code Examples
@Singleton
@Startup
@DependsOn("ConfigLoader")
// default for all methods: shared
@Lock(LockType.READ)
public class ExchangeRateCache {
@Inject RateClient client;
private volatile Map<String, BigDecimal> rates = Map.of();
@PostConstruct void load() { rates = Map.copyOf(client.fetchAll()); }
// READ: concurrent
public BigDecimal rate(String ccy) { return rates.get(ccy); }
@Lock(LockType.WRITE) // exclusive while refreshing
@AccessTimeout(value = 2, unit = TimeUnit.SECONDS)
@Schedule(minute = "*/10", hour = "*", persistent = false)
public void refresh() { rates = Map.copyOf(client.fetchAll()); }
}@Singleton
// developer-managed concurrency
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
public class Counters {
private final ConcurrentHashMap<String,
LongAdder> counters = new ConcurrentHashMap<>();
public void inc(String name) { counters.computeIfAbsent(name,
k -> new LongAdder()).increment(); }
public long get(String name) { LongAdder a
= counters.get(name); return a == null ? 0 : a.sum(); }
}5· Configuration, Defaults & Diagnostics
| Item | Default |
|---|---|
| Initialisation | Lazy (first use) unless @Startup |
| Concurrency management | CONTAINER |
| Lock type | WRITE for every method unless annotated |
| Access timeout | Vendor default (often several seconds) |
| Cluster | One instance per JVM |
A singleton bottleneck has a recognisable signature: throughput stops rising as load increases, CPU stays low, and latency grows evenly across every endpoint that touches the bean. A thread dump taken under load confirms it, showing many request threads parked inside the container's lock implementation for the same bean while one thread holds it. ConcurrentAccessTimeoutException in the logs is the same symptom once the access timeout expires. The fix is almost always to mark readers @Lock(READ) and shorten the write path, not to raise the timeout, which only makes callers wait longer before failing.
# Three thread dumps, ten seconds apart, while the load test runs
for i in 1 2 3; do jcmd <pid> Thread.print > dump-$i.txt; sleep 10; done
# Threads parked on a lock, then the frames around the bean
grep -c 'parking to wait for' dump-*.txt
grep -B2 -A12 'ExchangeRateCache' dump-2.txt | less
# Callers that gave up waiting
grep -c 'ConcurrentAccessTimeoutException' server.log6· Production Usage Patterns
- Reference-data caches refreshed by schedules.
- Startup initialisation (migrations checks, warm-up) with
@Startupand@DependsOn. - Coordinators for timers and background processing (with care in clusters).
7· Common Pitfalls & Misconceptions
- Forgetting
@Lock(READ)— default WRITE serialises all callers. - Long-running work under WRITE locks — requests pile up and time out.
- Assuming cluster-wide uniqueness — each node has its own singleton.
- Circular
@DependsOn— deployment failure.
8· Best Practices
- Annotate read-heavy singletons with
@Lock(READ)at class level. - Keep write-locked sections short; swap immutable snapshots.
- Set explicit
@AccessTimeout. - Use external coordination (DB locks, leader election) for cluster-wide singletons.
9· Architect's Perspective & Trade-offs
| Option | Concurrency control | Startup ordering | Best for |
|---|---|---|---|
EJB @Singleton | Declarative locks | @Startup, @DependsOn | Legacy EE apps, timers |
CDI @ApplicationScoped | Developer (java.util.concurrent) | @Observes Startup + priorities | Modern apps |
| Cluster singleton (vendor / leader election) | Distributed | Vendor-specific | Exactly-once jobs |
10· Interview Q&A
What is a singleton session bean?
A singleton session bean is an enterprise bean, annotated @Singleton, of which the container creates exactly one instance per application in each JVM and shares it among all clients. Unlike a stateless bean, which is pooled, its instance fields are genuinely shared, so it is the standard home for application-wide state such as reference-data caches, counters and registries. The container manages its lifecycle, optionally creating it eagerly with @Startup, ordering it with @DependsOn and calling @PostConstruct and @PreDestroy. It also manages concurrency through read and write locks. Because there is only one instance, every design decision about it is really a decision about thread safety and contention.
What does @Startup do?
@Startup tells the container to create and initialise the singleton while the application is deploying, rather than lazily on its first call. Its @PostConstruct therefore runs before the application serves traffic, which suits loading reference data, validating configuration or warming caches, and it runs in a transaction according to the bean's transaction attribute, so it can read the database. If initialisation fails, deployment usually fails too, which is the right outcome for mandatory configuration. @DependsOn names other singletons that must be initialised first and destroyed after this one. In CDI the equivalent is an @ApplicationScoped bean observing the Startup event, ordered with @Priority on the observed parameter.
What is the default concurrency behaviour of a singleton?
By default a singleton uses container-managed concurrency, and every business method has an implicit @Lock(WRITE), so the container lets only one thread into the bean at a time. Concurrent callers queue, which is safe but turns a bean called on every request into a serialisation point for the whole application. Methods or the whole class can be marked @Lock(LockType.READ), allowing any number of readers to run together while a WRITE method still waits for exclusive access. A sensible pattern is READ at class level and WRITE only on short mutating methods. Alternatively, @ConcurrencyManagement(BEAN) disables container locking and leaves thread safety to java.util.concurrent types.
What happens when a caller waits too long for a singleton lock?
The container waits up to the @AccessTimeout configured on the method or class, and if the lock is still unavailable it throws ConcurrentAccessTimeoutException, a system exception that rolls back any container-managed transaction. A value of 0 means fail immediately and -1 means wait indefinitely; without the annotation the vendor's default applies, often several seconds. Under load this shows up as request threads piling up behind one slow write-locked method, rising latency and finally a burst of these exceptions. Raising the timeout only lengthens the queue. The real fixes are READ locks for readers, keeping slow work such as remote calls outside the WRITE section, and swapping immutable snapshots instead of mutating shared state.
Is an EJB singleton unique across a cluster?
No. The specification guarantees one instance per application per JVM, so a four-node cluster has four independent singletons, each with its own state and its own timers. That is harmless for read-only caches, which simply refresh separately, but wrong for anything that must happen once: a scheduled billing run, a counter that must be globally accurate or a leader-only coordinator. Cluster-wide uniqueness needs coordination outside the bean, such as a vendor singleton service, a clustered persistent timer, a database lock row with an expiry, or leader election through Kubernetes leases or a consensus store. Whichever is used, the job must also tolerate failover, so it should be idempotent and resumable.
When would you keep an EJB singleton versus using a CDI bean?
I keep an EJB singleton in existing systems that rely on what it does declaratively: read/write locks, @Startup with @DependsOn ordering and EJB timers, because rewriting working concurrency code carries risk without business value. For new code I use an @ApplicationScoped CDI bean with explicit concurrency, usually an immutable snapshot in an AtomicReference or a ConcurrentHashMap, an observer of the Startup event for eager initialisation, and Jakarta Concurrency's managed scheduled executor instead of @Schedule. That is lighter, portable to runtimes without an EJB container such as Quarkus or Helidon, and easier to unit test. The main loss is declarative locking, which is rarely the right concurrency model anyway.
Test your knowledge on this topic →Flashcards from this topic's 6 questions, filtered by level and type.