ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 3 · Jakarta EE & Enterprise Java
  4. Volume VI
  5. Containers
Book 3 · Volume VI — Jakarta EE Platform Architecture & Enterprise Integration · Topic 1.4

Containers

A container is a managed execution environment. You hand it a class; it decides when the instance exists, which thread runs it, what identity it runs under, whether a transaction is open, and what gets injected into it. Your code is the payload, not the host.

18 min readStage 1 · Foundations12 interview questions
On this page
  1. 1. Concept
  2. 2. Why containers exist
  3. 3. The four containers
  4. 4. Internal mechanism: what happens around a call
  5. 5. Key building blocks
  6. 6. Worked example: one request, three containers
  7. 7. Common mistakes and anti-patterns
  8. 8. Performance, scalability and reliability
  9. 9. Security considerations
  10. 10. Trade-offs and alternatives
  11. 11. Evolution of the container model
  12. 12. How to verify this yourself
  13. 13. Interview questions and answers

1Concept

In an ordinary Java program you control object lifecycle: you call new, you decide when to release, you manage your own threads. In Jakarta EE you surrender that control. You declare a class as a component — with @Stateless, @RequestScoped, @WebServlet, @Path — and the container instantiates it, injects into it, invokes it, and destroys it.

In exchange for that control, the container supplies a set of services around every invocation: transactions, security, pooling, concurrency management, resource injection and lifecycle callbacks. This is inversion of control applied not to a few dependencies but to the entire runtime environment.

THE SINGLE MOST USEFUL SENTENCE IN THIS VOLUME Nothing the container provides is applied to an object the container did not create. Almost every confusing enterprise Java bug — missing transaction, ignored @RolesAllowed, silent interceptor, null injection point — reduces to a violation of that sentence.

2Why containers exist

The services a container supplies are the ones that are hardest to get right and most disastrous to get wrong: transaction demarcation, security enforcement, resource pooling, thread management. They are also cross-cutting — every component needs them, and every hand-rolled implementation differs subtly.

ConcernWithout a containerWith a container
TransactionsExplicit begin/commit/rollback in every method, with correct finally handling and nesting rules@Transactional or a transaction attribute; the container demarcates
SecurityEvery method checks the caller's roles by hand@RolesAllowed; the container enforces before the method body runs
Resource managementYou own connection pools, their sizing and their leak detectionInjected DataSource, pooled and monitored by the server
ConcurrencyYou create threads and hope you sized the pool correctlyContainer-managed request threads and managed executors that carry context
LifecycleManual construction and disposal, usually via a singleton registryScopes and contexts; the container creates and destroys
WiringConstructor plumbing or a service locator@Inject, resolved by type and qualifier at boot

The argument for containers is therefore not convenience. It is that transaction and security correctness should be declarative and auditable, not a matter of whether each developer remembered the right finally block.

The containers inside a Jakarta EE application server, and the services beneath them
Figure 1.4.1 — The containers inside a Jakarta EE application server, and the services beneath them

3The four containers

The specification defines four container types. Three live inside the server; one runs on the client.

3.1 The Web Container

Hosts everything driven by an HTTP request: servlets, filters, listeners, Jakarta Faces, Jakarta Pages, WebSocket endpoints and — in most runtimes — Jakarta RESTful Web Services resources.

  • Owns the request thread. It takes a thread from a pool, binds the request to it, and returns it afterwards. You do not create it and you must not keep it.
  • Owns the web lifecycle. ServletContext at application scope, HttpSession at session scope, HttpServletRequest per request.
  • Applies the filter chain before your servlet or resource method runs, and unwinds it afterwards.
  • Manages servlet instances as effective singletons. One servlet instance serves many concurrent requests — which is why servlet fields are shared mutable state and almost always a bug.

3.2 The CDI Container

CDI is the common component model that the other containers now build on. It is not a peer of the web and enterprise bean containers so much as the layer they both delegate to for injection, lifecycle and interception.

  • Bean discovery at deployment. Archives are scanned; beans are identified along with their types, qualifiers, scope and interceptor bindings.
  • Boot-time validation. Every injection point must resolve to exactly one bean. Ambiguous or unsatisfied dependencies fail deployment — not the first request.
  • Contexts. A scope such as @RequestScoped names a context; the context decides which instance answers for the current request, session or application.
  • Client proxies. For any normal scope, what is injected is a proxy, not the instance. The proxy consults the context on every call, which is how a @RequestScoped bean can be injected into an @ApplicationScoped one safely.
  • Interceptors, decorators and events — the extension points that let cross-cutting behaviour be added without touching the bean.
CDI container: boot-time discovery and validation, then per-call context resolution through a proxy
Figure 1.4.2 — CDI container: boot-time discovery and validation, then per-call context resolution through a proxy

3.3 The Enterprise Bean Container

Hosts @Stateless, @Stateful, @Singleton and @MessageDriven beans, and adds the services that predate CDI and are still its speciality: instance pooling, container-managed transactions, declarative security, container-managed concurrency and the timer service.

Bean typeInstance modelTypical use
@StatelessPooled; any instance may serve any call; no conversational stateThe default transactional service
@StatefulOne instance bound to one client for a conversation; may be passivated to diskMulti-step conversational state — a wizard or a cart
@SingletonExactly one instance per application, with container-managed read/write locksShared cached state, application startup work
@MessageDrivenPooled, invoked by the messaging provider rather than by a callerConsuming queues and topics (full Platform only)

3.4 The Application Client Container

The one container that does not live in the server. It runs in a standalone client JVM and gives a desktop or batch client a managed environment — injection, JNDI access to server resources, and a security identity — so that client code can be written in the same style as server components. It is rarely used today; most clients are browsers or HTTP APIs.

4Internal mechanism: what happens around a call

The mechanism that makes all of this work is interception through a proxy. When you inject a component, you almost never receive the instance. You receive a generated object that implements the same types, and it stands between the caller and the instance.

A call into an enterprise bean passes through the container's service chain before reaching your code
Figure 1.4.3 — A call into an enterprise bean passes through the container's service chain before reaching your code
  1. Security. The caller's identity is checked against @RolesAllowed. Failure throws before your code runs.
  2. Transactions. The container inspects the transaction attribute — REQUIRED, REQUIRES_NEW, MANDATORY and so on — and begins, joins or suspends accordingly.
  3. Interceptors. @AroundInvoke interceptors and decorators run in declared order.
  4. Instance acquisition. For a stateless bean, one is taken from the pool; for a stateful bean, the one bound to this client is located and possibly activated from disk.
  5. Your method runs.
  6. Unwind. Interceptors complete, the transaction commits or rolls back, the instance returns to the pool, and the security context is restored.

4.1 Threading model

The container owns the threads, and this is where the most damaging violations occur. A request thread carries a great deal of invisible state — the security identity, the transaction, the request context, the class loader. A thread you create yourself carries none of it.

CODE
// WRONG — an unmanaged thread has no context at all
@Stateless
public class ReportService {
    @Inject
    ReportGenerator generator;
    public void generateAsync(Long id) {
        new Thread(() -> generator.generate(id)).start();
        // no transaction, no security identity, no request scope,
        // possibly the wrong class loader, and invisible to monitoring
    }
}
Listing 1.4.1 — The classic violation. It usually appears to work in development and fails under load.
CODE
// RIGHT — a managed executor propagates context to the worker thread
@Stateless
public class ReportService {
    @Resource
    ManagedExecutorService executor;       // jakarta.enterprise.concurrent
    @Inject
    ReportGenerator generator;
    public void generateAsync(Long id) {
        executor.submit(() -> generator.generate(id));
    }
}
// Or, when you simply want the call to return immediately:
@Stateless
public class ReportService {
    @Asynchronous
    public void generateAsync(Long id) {
        // the container runs this on a managed thread with context intact
    }
}
Listing 1.4.2 — Both forms keep the work inside the container's world. See Volume III, Chapter 4 for the detail.

4.2 Deployment units and class loading

The container also owns class loading, and it uses it to isolate applications and modules from one another. Understanding the hierarchy is what turns NoClassDefFoundError from a mystery into a five-minute diagnosis.

Deployment units and the class loader hierarchy that isolates them
Figure 1.4.4 — Deployment units and the class loader hierarchy that isolates them
UnitExtensionContains
Web module.warServlets, REST resources, Faces views, WEB-INF/classes, WEB-INF/lib
Enterprise bean module.jarEnterprise beans and their interceptors
Resource adapter.rarA JCA connector
Enterprise application.earSeveral modules plus EAR/lib shared libraries

Delegation is parent-first by default: a class in EAR/lib wins over the same class in WEB-INF/lib. Most servers allow a WAR to be flipped to parent-last so the application's own version wins — the standard remedy when a server-supplied library collides with the version you need.

5Key building blocks

MechanismAnnotation / APIWhat the container does
Injection@Inject, @Resource, @PersistenceContext, @EJBResolves and supplies the dependency before first use
Lifecycle callbacks@PostConstruct, @PreDestroyCalls them after injection completes and before disposal
Scopes@RequestScoped, @SessionScoped, @ApplicationScoped, @DependentDecides which instance answers for the current context
Transactions@Transactional, @TransactionAttributeBegins, joins, suspends, commits or rolls back
Security@RolesAllowed, @PermitAll, @DenyAllEnforces before the method body executes
Interception@AroundInvoke, @Interceptors, interceptor bindingsWraps the invocation
ConcurrencyManagedExecutorService, @AsynchronousRuns work on a managed thread with context propagated
NamingJNDI, @Resource(lookup = …)Publishes and resolves server-managed resources

INJECTION HAPPENS AFTER CONSTRUCTION The container calls the constructor (or your @Inject constructor), then performs field injection, then calls @PostConstruct. Field-injected dependencies are therefore null inside a no-arg constructor. Initialisation that needs an injected dependency belongs in @PostConstruct — or use constructor injection, which avoids the problem entirely.

6Worked example: one request, three containers

A single HTTP request crossing the web, CDI and enterprise bean containers
Figure 1.4.5 — A single HTTP request crossing the web, CDI and enterprise bean containers
CODE
// --- Web container: the REST resource --------------------------
@Path("/orders")
@RequestScoped                                  // CDI manages this instance
public class OrderResource {
    @Inject
    OrderService orderService;                  // a proxy, not the instance
    @Inject
    CurrentUser currentUser;               // @RequestScoped, per request
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response place(@Valid OrderRequest request) {
        Order order = orderService.place(request, currentUser.getId());
        return Response.status(Response.Status.CREATED)
                       .entity(order)
                       .build();
    }
}
// --- Enterprise bean container: the transactional service --------
@Stateless
@RolesAllowed("customer")                  // enforced before the body
public class OrderService {
    @PersistenceContext
    private EntityManager em;                 // joins the transaction
    @Inject
    private InventoryService inventory;
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public Order place(OrderRequest request, Long customerId) {
        inventory.reserve(request.getItems());  // same transaction
        Order order = Order.from(request, customerId);
        em.persist(order);
        return order;                           // commit happens on return
    }
}
// --- CDI container: request-scoped state -------------------------
@RequestScoped
public class CurrentUser {
    @Inject
    private SecurityContext securityContext;   // jakarta.security
    private Long id;
    @PostConstruct
    void resolve() {                   // after injection, before use
        Principal principal = securityContext.getCallerPrincipal();
        this.id = (principal == null)
                ? null
                : Long.valueOf(principal.getName());
    }
    public Long getId() {
        return id;
    }
}
Listing 1.4.3 — Three containers cooperating. Note how little of the file is infrastructure.

Count what the application did not write: thread acquisition, request and session context activation, authentication, JSON deserialisation, bean validation, dependency resolution, transaction demarcation, connection acquisition from the pool, rollback on exception, context teardown, and thread return. That is the container's contribution, and it is most of the hard part.

6.1 What happens when it goes wrong

CODE
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public Order place(OrderRequest request, Long customerId) {
    inventory.reserve(request.getItems());
    Order order = Order.from(request, customerId);
    em.persist(order);
    if (order.getTotal().compareTo(creditLimit) > 0) {
        throw new CreditLimitExceededException();  // unchecked → rollback
    }
    return order;
}
Listing 1.4.4 — The reservation is rolled back too, because both calls joined the same transaction.

The rule the container applies: an unchecked exception escaping a bean method marks the transaction for rollback automatically; a checked exception does not, unless the exception class is annotated @ApplicationException(rollback = true). This catches a great many people, and it is worth stating explicitly in a code review checklist. Volume IV, Chapter 5 covers the rules in full.

7Common mistakes and anti-patterns

7.1 Creating components with new

CODE
// WRONG — the container never sees this object
@Stateless
public class OrderService {
    public void place(OrderRequest r) {
        // no injection, no transaction, no security, no interception
        InventoryService inv = new InventoryService();
        inv.reserve(r.getItems());
    }
}

The object is a plain Java object. Its @PersistenceContext field is null, its @RolesAllowed is decorative, and its transaction attribute means nothing. It will usually throw a NullPointerException on first use — which is the lucky outcome, because the unlucky one is that it works and silently runs outside the transaction.

7.2 Self-invocation

CODE
@Stateless
public class OrderService {
    public void placeAll(List<OrderRequest> requests) {
        for (OrderRequest r : requests) {
            this.placeOne(r);      // direct call — bypasses the proxy
        }
    }
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void placeOne(OrderRequest r) {
        // this will NOT get its own transaction when called as above
    }
}
Listing 1.4.5 — The most under-diagnosed bug in enterprise Java.

this is the instance, not the proxy. The call goes straight to the method body and skips security, transactions and interceptors. The fixes are to inject the bean into itself, to obtain the proxy via SessionContext.getBusinessObject(), or — usually best — to split the two responsibilities into separate beans so that the call genuinely crosses a boundary.

7.3 Other recurring ones

  • Mutable instance fields on a servlet or a stateless bean. A servlet is effectively a singleton serving concurrent requests; a stateless bean is pooled and may serve a different caller on the next call. Fields are shared or stale — either way, wrong.
  • Creating your own threads. No transaction, no identity, no context, and invisible to the server's monitoring and shutdown sequence. Use a ManagedExecutorService.
  • Doing work in a constructor that needs injection. Field injection has not happened yet. Use @PostConstruct.
  • Holding a @RequestScoped reference in application-scoped state. Injection is safe because you get a proxy; caching the resolved instance is not — you will leak one request's data into another's.
  • Opening files, sockets or a JDBC connection directly. Bypasses pooling, monitoring and transaction enrolment. Inject a DataSource.
  • Assuming @PreDestroy always runs. On a kill, a crash or a pool eviction under memory pressure it may not. Never rely on it for data integrity — that is what transactions are for.
  • Calling System.exit() or installing a shutdown hook. You share the JVM with every other application on that server.

8Performance, scalability and reliability

MechanismWhat it buysWhat to watch
Stateless bean poolingInstance reuse without construction cost; a natural concurrency limitPool too small → callers queue. Pool too large → the database becomes the bottleneck instead.
Connection poolingConnection reuse; a hard ceiling on database loadPool size should relate to database capacity, not to thread count. Leaks appear as timeouts under load, not as errors.
Request thread poolsBounded concurrency and back-pressureA blocking downstream call holds a thread for its whole duration. This is the classic thread-pool exhaustion cascade.
Stateful bean passivationMemory relief for idle conversationsSerialisation cost and disk I/O; a common source of surprising latency spikes.
Virtual threads (Jakarta EE 11)Far higher concurrency for blocking I/O workloadsOnly on Java 21+. Do not pin virtual threads with synchronized blocks around I/O.
Interception chainsDeclarative cross-cutting behaviourEvery layer costs a call. Deep interceptor stacks on a hot path are measurable.

The reliability point worth internalising: the container's pools are the system's back-pressure mechanism. When they are sized correctly, overload manifests as queuing and timeouts you can observe. When they are unbounded — or bypassed by application-created threads — overload manifests as an out-of-memory error and a dead JVM.

9Security considerations

  • Identity propagation is a container service. The caller identity established at the web tier flows into the enterprise bean container automatically — but only along container-managed call paths. A thread you created yourself has no identity, so @RolesAllowed on anything it calls will fail or, worse, run unauthenticated.
  • @RolesAllowed is enforced by the proxy. Self-invocation therefore bypasses it, exactly as it bypasses transactions. A “private” helper method that carries a role annotation gives false assurance.
  • Deny by default where you can. @DenyAll at class level with @RolesAllowed on the specific methods that should be open is more defensible than the reverse, because adding a new method then fails closed.
  • Class loader isolation is a security boundary. One application cannot see another's classes. Sharing state through static fields in a server-wide library deliberately punches a hole through it.
  • Injected resources carry credentials you did not manage. A DataSource obtained from JNDI uses the credentials configured on the server — which is precisely why they should not also be sitting in a properties file in the WAR.
  • SecurityManager is gone. Jakarta EE 11 removed the requirement, aligning with JEP 411. If an old design relied on it for in-JVM isolation between applications, that design needs revisiting — isolation is now a process and container concern.

10Trade-offs and alternatives

ModelStrengthsCostsFits
Full application server
(WildFly, WebLogic, Open Liberty)
Every service standardised; multiple applications per server; mature operations toolingLarge footprint; slow start; shared-JVM blast radius; server configuration is vendor-specificConsolidated enterprise estates, integration-heavy systems
Profile-sized runtime
(Web or Core Profile server)
Same programming model, smaller surface; good container fitMust confirm the profile actually covers your needsMost new Jakarta EE services
MicroProfile on a Jakarta EE core
(Open Liberty, Quarkus, Helidon)
Standard component model plus config, health, metrics, fault toleranceMicroProfile is a separate specification set with its own release cadenceCloud-native services that want standards
Spring BootEnormous ecosystem; fast iteration; embedded runtimeSingle implementation; the runtime is a dependency rather than a platformTeams already fluent in Spring
Plain Java + librariesTotal control; minimum magicYou now own transactions, security, pooling and lifecycle — and their bugsNarrow, well-understood services

The honest summary: containers trade explicitness for correctness. You give up the ability to read a method and see everything that happens, and you get transaction and security behaviour that is uniform across a large codebase and enforceable by review. For a five-class service that trade is poor value; for a two-hundred-class system maintained by rotating teams it is usually decisive.

11Evolution of the container model

EraContainer model
J2EEHeavyweight, descriptor-driven. Components implemented framework interfaces and could not be tested outside the server.
Java EE 5Annotation-driven. Components became plain objects; the container's role became interception rather than inheritance.
Java EE 6CDI arrives and begins unifying the component models. The Web Profile makes a smaller container legitimate.
Java EE 7 / 8Container-managed concurrency and batch standardised. The container's remit grows sideways rather than downwards.
Jakarta EE 10CDI split into Lite and Full; the Core Profile makes a build-time-resolvable container possible.
Jakarta EE 11Virtual thread support in Jakarta Concurrency; SecurityManager requirement removed; CDI becomes more firmly the foundation, with Managed Beans deprecated.

The direction of travel is consistent: less of the container visible in your code, and more of it resolved before runtime. The heavyweight interfaces went first, then the descriptors, and now the runtime classpath scanning is going too, because build-time resolution is what native images require.

12How to verify this yourself

  1. Verify the proxy exists. Inject a @Stateless bean and log bean.getClass().getName(). You will see a generated class name — $Proxy or a vendor-specific suffix — not your class.
  2. Verify self-invocation bypasses the container. Write the two methods from Listing 1.4.5, put a logging interceptor on the inner one, and observe that it never fires on the internal call. Then inject the bean into itself and watch it fire.
  3. Verify pooling. Log System.identityHashCode(this) in a stateless bean method and fire concurrent requests. You will see a small, repeating set of identities rather than one per request.
  4. Verify context loss on unmanaged threads. Call SecurityContext.getCallerPrincipal() inside a new Thread(...) and compare it with the same call on the request thread.
  5. Verify class loader isolation. Deploy the same library at two different versions in two WARs on one server. Both work; neither sees the other.
  6. Verify boot-time validation. Add a second implementation of an injected interface without a qualifier. Deployment fails with an ambiguous-dependency error — before any request arrives.

13Interview questions and answers

Q1Concept

What is a container in Jakarta EE, and what does it actually do?

It is the managed execution environment that owns your components' lifecycle and applies services around every invocation. Concretely it creates instances, injects dependencies, calls lifecycle callbacks, allocates the thread, establishes the security identity, demarcates transactions, runs interceptors, supplies pooled resources, and cleans all of it up afterwards.

The defining rule is that none of those services apply to an object the container did not create. That one sentence explains most of the surprising behaviour people hit in enterprise Java.

Q2Concept

Name the containers defined by the platform and what each is responsible for.

  • Web container — servlets, filters, listeners, Faces, Pages, WebSocket, and usually REST resources. Owns request threads, sessions and the filter chain.
  • Enterprise bean container — stateless, stateful, singleton and message-driven beans. Owns pooling, container-managed transactions, declarative security, container-managed concurrency and timers.
  • CDI container — bean discovery, contexts and scopes, client proxies, producers, events, interceptors and decorators. In modern Jakarta EE it is the common model the others build on.
  • Application client container — runs on the client JVM, giving standalone client code injection and JNDI access to server resources. Rarely used today.
Q3Tricky

Why is calling a method on this inside a bean different from calling it through an injected reference?

Because the container's services are applied by a proxy that sits between caller and instance. An injected reference points at the proxy; this points at the instance.

A call through the proxy passes security checks, transaction demarcation and the interceptor chain. A call on this goes straight to the method body and skips all of it. So a method annotated REQUIRES_NEW called internally does not get its own transaction, and a method annotated @RolesAllowed called internally is not access-checked.

The fixes are to inject the bean into itself, to use SessionContext.getBusinessObject(), or — cleaner — to move the annotated method to a separate bean so the call genuinely crosses a container boundary. I prefer the last one: if a method needs its own transaction, that is usually a sign it is a separate responsibility.

Q4Internals

What is the difference between a stateless and a stateful session bean, from the container's point of view?

A stateless bean is pooled. The container keeps a small set of instances and hands any of them to any caller for the duration of a single method call. There is no association between a caller and an instance, which is why instance fields are unsafe — the next call may land on a different instance, or the same instance may serve a different caller.

A stateful bean is bound to one client for a conversation spanning multiple calls. The container keeps that association, may passivate the instance to disk when it is idle, and destroys it on @Remove or timeout. That gives you conversational state, at the cost of memory, passivation I/O and an affinity problem in a cluster.

Q5Tricky

Why is creating your own thread inside a container a problem?

Because a container-managed thread carries invisible state that an unmanaged thread does not: the transaction, the security identity, the active CDI contexts, the correct context class loader, and the server's own tracking for monitoring and graceful shutdown.

Work on a raw new Thread(...) runs with none of that. In development it usually appears to work, because the code path that needs the identity or the transaction has not been exercised. Under load or after a security requirement is added, it fails — and it fails in a way that is hard to trace back.

The correct tools are ManagedExecutorService, ManagedScheduledExecutorService or @Asynchronous, all of which propagate context onto the worker thread and remain visible to the server.

Q6Internals

How do CDI scopes work, and why is a proxy involved?

A scope names a context — an object that decides which bean instance is current. @RequestScoped is answered by the request context, @SessionScoped by the session context, and so on.

The proxy exists to make the lookup lazy and per-call. If a @RequestScoped bean were injected directly into an @ApplicationScoped one, the application-scoped bean would capture a single request's instance and hand it to every subsequent request — a serious data leak. Instead the injected reference is a proxy that asks the context on every invocation, so it always resolves to the correct instance for the current request.

@Dependent is the exception: it is a pseudo-scope, it gets no proxy, and the instance's lifecycle is tied to the object that injected it.

Q7Scenario

A @PersistenceContext field is null. What are the likely causes?

In order of how often I have actually seen each:

  • The object was created with new rather than obtained from the container, so no injection happened at all.
  • The code is running in a constructor — field injection occurs after construction, so the field is legitimately null there. It belongs in @PostConstruct.
  • The class is not a managed bean: no bean-defining annotation, or the archive is not a bean archive because beans.xml is missing and no annotation makes it implicit.
  • The injection is in a superclass that the container does not treat as part of the managed bean.
  • The persistence unit name is ambiguous because more than one unit is defined and none was named.

The first two account for the large majority.

Q8Internals

What does the container do when an exception escapes a bean method?

It depends on the kind of exception. An unchecked exception (a RuntimeException or Error) escaping a bean method marks the transaction for rollback automatically, and for a stateless bean the container also discards the instance rather than returning it to the pool. A checked exception does not cause rollback by default.

That default is overridable: @ApplicationException(rollback = true) on a checked exception makes it roll back, and @ApplicationException(rollback = false) on an unchecked one makes it not. Teams routinely get caught by the checked-exception default, so I make it an explicit review item — either annotate your application exceptions deliberately, or call setRollbackOnly() where it matters.

Q9Internals

How does class loader isolation work in an application server, and when does it bite?

Each deployed application gets its own class loader, and within an EAR each module gets one too, with EAR/lib shared above them. Delegation is parent-first by default, so a class visible to the parent wins over the same class in WEB-INF/lib.

It bites in two ways. The first is version collision: the server supplies version 1 of a library, your WAR bundles version 2, and parent-first means you get version 1 — often with a NoSuchMethodError rather than anything informative. The remedy is to flip the WAR to parent-last, or to stop bundling it.

The second is duplicate platform APIs: bundling jakarta.servlet-api in WEB-INF/lib gives you two copies of the same class loaded by different loaders. The symptom is a ClassCastException saying that a type cannot be cast to itself, which reads as nonsense until you realise class identity includes the loader. Platform APIs should always be provided.

Q10Concept

Why does the container validate injection points at deployment rather than at first use?

Because a wiring error is a deployment defect, and a deployment defect should stop a deployment — not surface at three in the morning when the first request happens to hit that code path.

CDI requires every injection point to resolve to exactly one bean. Ambiguous resolution (two candidates, no qualifier) and unsatisfied resolution (no candidate) both fail the deployment with a message naming the injection point. It is a fail-fast design, and it is one of CDI's genuinely strong properties: the class of bug that plagues reflection-based wiring at runtime is largely eliminated.

It is also the reason CDI Lite exists — moving even more of that resolution to build time is what makes ahead-of-time compilation possible.

Q11Trade-off

When would you not use a Jakarta EE container?

When the trade is bad value. Containers exchange explicitness for uniform correctness, and that pays off with scale and team turnover. For a genuinely small, narrow service — a handful of classes, one developer, no transactional complexity — a plain Java application with a couple of libraries is easier to reason about and easier to operate.

I would also think hard about it where the team has deep Spring fluency and no Jakarta EE experience. The technical arguments between the two are much narrower than the organisational ones; picking the stack your people can debug at 3 a.m. usually beats picking the one that scores better on a comparison table.

What I would not do is adopt a container and then fight it — creating threads, new-ing components, managing transactions by hand. That is the worst of both worlds: the footprint of a container with none of the guarantees.

Q12Concept

How does Jakarta EE 11 change the container's threading model?

Jakarta Concurrency 3.1 adds virtual thread support for applications running on Java 21 or later. A managed executor can be defined to use virtual threads, so blocking I/O workloads can scale to far higher concurrency without a correspondingly large platform thread pool.

The important part is that this happens inside the container's concurrency model, so context propagation — transaction, security identity, CDI contexts — still works. That is the difference between using virtual threads properly and spawning them yourself, which reintroduces every problem described earlier in this note.

The usual caveat applies: virtual threads help blocking workloads, not CPU-bound ones, and pinning caused by synchronized blocks around I/O will undo the benefit. It is a scalability change, not a free speed-up.

Test your knowledge on this topic →Flashcards from this topic's 12 questions, filtered by level and type.

Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.