Java EE / Jakarta EE

Enterprise Beans 4: Stateless, Stateful and Singleton Session Beans

Intermediate9 min readUpdated

Session beans are the business-tier components of Jakarta EE: the container instantiates them, pools them, wraps every call in a transaction and a security check, and can run them asynchronously or on a schedule. This guide explains stateless, stateful and singleton beans, their views and life cycles, interceptors, timers and concurrency control, then draws the line between what still needs an enterprise bean and what a plain CDI bean does just as well.

What you will learn

  • Choose between stateless, stateful and singleton session beans for a given use case
  • Expose a bean through no-interface, local and remote views and understand what each costs
  • Use container services: transactions, declarative security, interceptors, timers and asynchronous methods
  • Control concurrency in singleton beans with @Lock and understand pooling and passivation
  • Decide when a CDI bean with @Transactional replaces an enterprise bean

Enterprise JavaBeans is the part of the platform with the worst reputation and the best excuse: version 2.x, with its home interfaces, mandatory RemoteExceptions and hundreds of lines of XML per component, is what people remember. Version 3.0 (2006) replaced all of it with plain classes and a handful of annotations, and since then the specification — now Jakarta Enterprise Beans 4.0 — has been a compact way to say "run this class inside the container and give it transactions, security, pooling and scheduling". Understanding what that buys, and what CDI now provides on its own, lets you use enterprise beans where they pay for themselves and nowhere else.

What the container does for a session bean

A session bean is a class annotated with @Stateless, @Stateful or @Singleton. You never instantiate it; the container does, and every call from a client goes through a proxy that the container puts in front of the instance. The proxy is where the platform services hook in:

  • Transactions — by default every business method runs in a JTA transaction (REQUIRED), started if none exists and committed when the outermost method returns; a runtime exception rolls it back. The transactions guide covers the attributes in depth.
  • Security — @RolesAllowed, @PermitAll, @DenyAll on the class or method are enforced before the call; SessionContext.getCallerPrincipal() tells you who is calling.
  • Concurrency — the container guarantees single-threaded access to stateless and stateful instances, so bean code needs no locks.
  • Injection — @Inject, @EJB, @PersistenceContext, @Resource fields are populated before @PostConstruct runs.
  • Interception — life-cycle callbacks and @AroundInvoke interceptors run around methods.
  • Remoting, scheduling and asynchrony — remote views, @Schedule timers and @Asynchronous methods are available only on enterprise beans.

The price is the proxy: calling a method on this bypasses it, and every managed call carries some overhead. Neither is significant in normal code, but both explain a whole class of "my annotation is ignored" bugs.

Stateless session beans

The workhorse. A stateless bean holds no conversational state between calls, so the container keeps a pool of instances and lends one to each invocation. Two consecutive calls from the same client may hit two different instances; instance fields are therefore only for injected resources and immutable configuration.

package shop.service;

import java.util.List;
import jakarta.annotation.security.RolesAllowed;
import jakarta.ejb.Stateless;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;

@Stateless
public class OrderService {

    @PersistenceContext(unitName = "shop")
    EntityManager em;                       // container-managed, transaction-scoped

    public List<Order> find(String customer, OrderStatus status) {
        return em.createQuery("""
                select o from Order o
                where o.customer.name = :customer
                  and (:status is null or o.status = :status)
                order by o.placedAt desc""", Order.class)
            .setParameter("customer", customer)
            .setParameter("status", status)
            .getResultList();
    }

    @RolesAllowed("sales")
    public Order place(Long customerId, List<OrderLine> lines) {
        Customer customer = em.getReference(Customer.class, customerId);
        Order order = new Order(customer, lines);
        em.persist(order);                  // committed when this method returns normally
        return order;
    }
}

There is no interface, no descriptor and no explicit transaction. find and place each run inside a transaction started by the container, place is only callable by users in the sales role, and the EntityManager is bound to that transaction. This is the no-interface view introduced in EJB 3.1: clients inject the class directly.

@Inject OrderService orderService;      // CDI injection works for session beans
@EJB   OrderService orderService;       // the older enterprise-bean-specific injection; still valid

Pool sizes are vendor settings (WildFly's strict-max-pool, Open Liberty's maxPoolSize, and so on). When the pool is exhausted callers wait, which makes the pool a natural throttle in front of a database — set it with the connection pool size in mind.

Stateful session beans

A stateful bean keeps state for one client across several calls: a shopping cart, a multi-step wizard, a workflow that accumulates data before committing. The container creates a fresh instance when the client first obtains a reference and destroys it when a method annotated @Remove completes or the bean times out (@StatefulTimeout).

import java.util.concurrent.TimeUnit;
import jakarta.ejb.Remove;
import jakarta.ejb.Stateful;
import jakarta.ejb.StatefulTimeout;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.PersistenceContextType;

@Stateful
@StatefulTimeout(value = 30, unit = TimeUnit.MINUTES)
public class Checkout {

    @PersistenceContext(unitName = "shop", type = PersistenceContextType.EXTENDED)
    EntityManager em;                       // extended: entities stay managed across calls

    private Order draft;

    public void start(Customer customer) { draft = new Order(customer); }
    public void add(Product p, int qty)  { draft.addLine(p, qty); }

    @Remove
    public Order confirm() {
        em.persist(draft);                  // the extended context flushes here, inside the transaction
        return draft;
    }

    @Remove
    public void cancel() { draft = null; }
}

Two things distinguish stateful beans from a CDI @SessionScoped bean. First, the extended persistence context: entities loaded in one call remain managed in the next, without merges, until the transaction that ends the conversation commits — the only place in the platform where that is possible. Second, passivation: an idle stateful bean can be serialised to disk to free memory, so its fields must be serialisable or transient, exactly like a view-scoped Faces bean. In practice stateful beans are rare; most conversational state lives in the web tier, and the extended persistence context is their main remaining justification.

Singleton session beans

A singleton is instantiated once per application and shared by all clients, which makes it the place for caches, start-up work and coordination. Because it is shared, the container has to manage concurrent access, and the specification gives you two modes.

import jakarta.annotation.PostConstruct;
import jakarta.ejb.*;

@Singleton
@Startup                                   // create at deployment, not at first use
@DependsOn("ConfigurationLoader")          // order start-up relative to another singleton
@Lock(LockType.READ)                       // default for all methods: concurrent readers
public class ExchangeRates {

    private Map<String, BigDecimal> rates = Map.of();

    @PostConstruct
    void load() { rates = fetchFromProvider(); }

    public BigDecimal rate(String currency) { return rates.get(currency); }   // READ lock

    @Lock(LockType.WRITE)                  // exclusive: readers wait until refresh finishes
    @Schedule(hour = "*", minute = "0", persistent = false)
    public void refresh() { rates = fetchFromProvider(); }

    @AccessTimeout(value = 5, unit = TimeUnit.SECONDS)   // fail rather than block forever
    @Lock(LockType.WRITE)
    public void override(String currency, BigDecimal rate) { /* ... */ }
}

With container-managed concurrency (the default), @Lock(READ) methods run in parallel and @Lock(WRITE) methods run exclusively — the read/write-lock pattern without writing a lock. The default lock for a singleton is WRITE, which serialises every call, so declare READ at class level and mark the mutators. @ConcurrencyManagement(BEAN) switches the container off and lets you use synchronized or java.util.concurrent yourself.

@Startup singletons are the platform's answer to "run this when the application starts"; combined with @DependsOn they give ordered initialisation. CDI 4.0 offers an alternative — observing @Initialized(ApplicationScoped.class) — that does not need an enterprise bean.

Views: no-interface, local and remote

A bean exposes one or more views, and the view determines what the proxy looks like to clients:

ViewDeclared byCall semanticsUse when
No-interfaceNothing (public methods of the class)In-JVM, by referenceAlmost always
Local@Local interfaceIn-JVM, by referenceYou want an interface for testing or several implementations
Remote@Remote interfaceCross-JVM, by value (serialised)A different process must call the bean

Remote calls look identical in code and behave completely differently: every argument is copied, every result is copied back, a network round trip happens, and failures surface as EJBException wrapping the cause. A remote client outside the server looks the bean up by its portable JNDI name using vendor-provided client libraries:

var props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.wildfly.naming.client.WildFlyInitialContextFactory");
props.put(Context.PROVIDER_URL, "remote+http://app-server:8080");
var ctx = new InitialContext(props);
var orders = (OrderServiceRemote) ctx.lookup("ejb:/shop/OrderService!shop.service.OrderServiceRemote");

The J2EE-era habit of splitting an application into a web tier calling a remote business tier is almost always a mistake today; if two processes must talk, a REST or messaging boundary is easier to evolve, secure and monitor. Enterprise Beans 4.0 made CORBA/IIOP interoperability optional and dropped EJB 2.x entity beans and JAX-RPC endpoints altogether, so the remaining remote protocols are vendor-specific.

Life cycle callbacks and interceptors

Every session bean can annotate a method with @PostConstruct (after injection, before the first business call) and @PreDestroy (before the instance is discarded); stateful beans add @PrePassivate and @PostActivate. These are the places for opening and closing resources the bean owns.

Interceptors wrap business methods and are the enterprise-bean equivalent of aspects. An interceptor class declares an @AroundInvoke method that receives an InvocationContext and must call proceed():

import jakarta.interceptor.AroundInvoke;
import jakarta.interceptor.Interceptor;
import jakarta.interceptor.InvocationContext;

@Timed @Interceptor @Priority(Interceptor.Priority.APPLICATION)
public class TimingInterceptor {

    @AroundInvoke
    Object time(InvocationContext ctx) throws Exception {
        long start = System.nanoTime();
        try {
            return ctx.proceed();
        } finally {
            log.info("{}.{} took {} µs", ctx.getTarget().getClass().getSimpleName(),
                     ctx.getMethod().getName(), (System.nanoTime() - start) / 1000);
        }
    }
}

@Timed here is a CDI interceptor binding — an annotation you define with @InterceptorBinding — so any bean or method annotated @Timed gets the interceptor. The older @Interceptors(TimingInterceptor.class) annotation from the Enterprise Beans specification still works but couples the bean to the interceptor class. Interceptors run inside the container's own transaction and security interception, in @Priority order, and they apply to CDI beans as well as to session beans; the interceptor model is shared.

Timers and asynchronous methods

@Schedule declares a calendar-based timer with cron-like fields (second, minute, hour, dayOfWeek, dayOfMonth, month, year, plus timezone). Timers are persistent by default: the container stores them and fires missed runs after a restart, which is what you want for a nightly job and exactly what you do not want for a cache refresh — hence persistent = false above. For timers created at runtime, inject TimerService and call createCalendarTimer or createIntervalTimer; the callback is a method annotated @Timeout. On a cluster, persistent timers fire on one node only; non-persistent timers fire on every node.

@Asynchronous makes the container run a method on a separate thread and return immediately. A void method is fire-and-forget; a method returning Future<T> lets the caller collect the result or cancel:

@Asynchronous
public Future<Invoice> generateInvoice(Long orderId) {
    Invoice invoice = render(orderId);          // runs in its own transaction, on a container thread
    return new AsyncResult<>(invoice);
}

The asynchronous method runs in a new transaction context (the caller's does not propagate) and its security context is propagated. Jakarta Concurrency's ManagedExecutorService covers similar ground for non-bean code; @Asynchronous is the simpler option when the work already lives in a bean, and CDI 4.0-era servers also support Jakarta Concurrency 3.0's @Asynchronous on CDI beans, which returns a CompletableFuture.

Enterprise beans or CDI beans?

CDI arrived in Java EE 6 and has absorbed most of what once required an enterprise bean. The decision today:

NeedCDI beanSession bean
Injection, scopes, events, interceptors, decoratorsYesYes (through CDI)
Transactions@Transactional (JTA 1.2+)@TransactionAttribute, default REQUIRED on every method
Declarative role checksProgrammatic via SecurityContext.isCallerInRole; @RolesAllowed on CDI beans only as a vendor extension@RolesAllowed everywhere
Pooling and instance throttlingNoStateless pool
Remote interfaceNo@Remote
Message consumptionNo (except vendor extensions)Message-driven beans
Calendar timersProgrammatic only (ManagedScheduledExecutorService); Jakarta Concurrency 3.1 in EE 11 adds scheduled async methods@Schedule, TimerService
Extended persistence contextNoStateful bean
Start-up ordering@Initialized observer@Startup + @DependsOn
AvailabilityEvery profile including CoreWeb Profile (Lite) or Platform

A reasonable rule: write services as @ApplicationScoped CDI beans with @Transactional unless you need a feature from the right-hand column, in which case the extra annotation costs nothing. Codebases from the Java EE 6 and 7 era lean the other way — @Stateless on everything — and there is no urgency to convert them; the two models interoperate without friction.

Common mistakes

  • Calling this.otherMethod() and expecting REQUIRES_NEW or @RolesAllowed to apply. The proxy is bypassed. Inject the bean into itself (@Inject OrderService self;) and call self.otherMethod().
  • State in a stateless bean. A field set in one method and read in another will work in tests with one instance and fail under load when the pool hands out a different instance.
  • Singletons with the default WRITE lock. Every call is serialised; throughput collapses under concurrency. Put @Lock(READ) on the class.
  • Persistent timers for volatile work. After a restart the container replays every missed firing. Use persistent = false for refreshes and heartbeats.
  • Remote views inside one deployment. Copying arguments for a call within the same JVM is pure overhead. Use the no-interface or local view.
  • Catching the runtime exception inside the bean and returning normally. The transaction is already marked for rollback by the time an EJBException reaches the caller; if you catch it yourself, check sessionContext.getRollbackOnly() or throw an @ApplicationException instead.
  • Non-serialisable fields in stateful beans. Passivation throws; mark them transient and rebuild them in @PostActivate.

Key takeaways

  • A session bean is a container-managed class behind a proxy; the proxy supplies transactions, security checks, single-threaded access, injection and interceptors.
  • Stateless beans are pooled and hold no client state; stateful beans keep per-client state and can own an extended persistence context; singletons are shared and need @Lock to allow concurrent reads.
  • Prefer the no-interface view; use @Remote only across processes, and prefer REST or messaging for that boundary.
  • Timers (@Schedule, TimerService) and @Asynchronous methods are container features unavailable to plain objects; make timers non-persistent unless missed runs must be replayed.
  • Interceptors, life-cycle callbacks and injection are shared with CDI; a CDI bean plus @Transactional replaces most stateless beans.
  • Enterprise Beans 4.0 dropped EJB 2.x entity beans and JAX-RPC; the specification is stable and unlikely to change further.

Sources and further reading

Frequently asked questions

Are EJBs still used, or has CDI replaced them?
Both are used. CDI handles injection, scopes, events and — with @Transactional — transactions, so a large share of new business logic is written as CDI beans. Enterprise beans remain the standard way to get remote interfaces, message-driven consumers, timers, @Asynchronous methods, declarative role checks and singleton start-up logic on a Jakarta EE server. The specification is stable rather than evolving: version 4.0 has been unchanged since Jakarta EE 9.
Why is a stateless bean pooled if it has no state?
Because creating one is not free: the container has to run injection, resolve resources and call @PostConstruct. Keeping a pool of initialised instances lets the container hand a request an instance immediately and guarantees that only one thread uses an instance at a time, so your code never needs synchronisation. The pool size caps concurrency, which is also a useful throttle.
What is the difference between a local and a remote interface?
A local view is a call within the same JVM: arguments are passed by reference and the overhead is a proxy call. A remote view (@Remote) is designed to be called from another JVM over a vendor protocol: arguments and results are serialised and passed by value, exceptions are wrapped in EJBException, and the call is orders of magnitude slower. Use remote only when there is really a second process.
Can I call a session bean method from another method of the same bean and get a new transaction?
Not by calling it directly with this — the container proxy is bypassed, so no transaction attribute, security check or interceptor applies. Inject the bean into itself through its business interface (or SessionContext.getBusinessObject) and call through that reference.