ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 3 · Jakarta EE & Enterprise Java
  4. Volume V
  5. JMS Architecture
Book 3 · Volume V — Messaging, JSON, Security & Validation · Topic 1.2

JMS Architecture

Connection, Session, Destination, Producer, Consumer

8 min readStage 1 · Foundations8 interview questions
On this page
  1. 1. · Concept & Definition
  2. 2. · Why It Matters
  3. 3. · How It Works
  4. 4. · Java / Jakarta EE Code Examples
  5. Deep Dive — Threading, Pooling and Resource Leaks
  6. Deep Dive — Connection Loss and Reconnection
  7. 5. · Configuration, Defaults & Diagnostics
  8. 6. · Production Usage Patterns
  9. 7. · Common Pitfalls & Misconceptions
  10. 8. · Best Practices
  11. 9. · Architect's Perspective & Trade-offs
  12. 10. · Interview Q&A

1· Concept & Definition

The JMS API is built from five objects. A connection factory creates a connection to the broker; a connection creates sessions, each of which is a single-threaded context for sending and receiving; a session creates producers and consumers bound to a destination. Jakarta Messaging 2.0 added JMSContext, which combines connection and session into one injectable, auto-closing object — the form almost all new code should use.

From connection factory to producer and consumer
Figure 1.2.1 — From connection factory to producer and consumer

2· Why It Matters

  • The object model determines thread safety: sessions are not shareable, and misuse produces intermittent corruption.
  • Connections are expensive; sessions are cheap — knowing which to pool decides throughput.
  • The classic and simplified APIs coexist in real code bases, and both appear in interviews.
  • Acknowledgement and transaction behaviour are configured on the session, so the session is where Chapter 2's semantics are chosen.

3· How It Works

Connection

AspectDetail
Created fromConnectionFactory (injected, or JNDI lookup)
CostA TCP connection plus authentication — pool it, never create per message
StateMust be start()ed before consumers receive; producers may send before
Client identifierRequired for durable subscriptions: identifies the client across restarts
Exception listenersetExceptionListener reports connection loss asynchronously
Thread safetyThe connection itself is thread-safe; the sessions it creates are not

Session

A session is a single-threaded context. It defines the acknowledgement mode or transactional behaviour, creates producers, consumers, destinations and messages, and provides the ordering guarantee — messages sent on one session to one destination arrive in order. Sharing a session across threads is undefined behaviour and the source of some of the hardest-to-reproduce defects in messaging code.

Session modeMeaning
AUTO_ACKNOWLEDGEAcknowledged when onMessage returns or receive completes
DUPS_OK_ACKNOWLEDGELazy batched acknowledgement; duplicates possible
CLIENT_ACKNOWLEDGEApplication calls acknowledge(), confirming all prior messages
SESSION_TRANSACTEDcommit() / rollback() on the session
Container-managedIn an MDB, the JTA transaction decides (Chapter 2)

Destination

A destination is a Queue or Topic object. It should be obtained by injection or lookup from a configured resource, not created by name at runtime: definitions live in deployment descriptors, @JMSDestinationDefinition, or the broker's own configuration, so that environments can differ without code changes. Temporary destinations (createTemporaryQueue) exist for request/reply and disappear with the connection.

Producer

SettingAPIEffect
Delivery modesetDeliveryMode(PERSISTENT / NON_PERSISTENT)Whether the broker writes it to disk
PrioritysetPriority(0–9)Best-effort ordering hint; support varies
Time to livesetTimeToLive(ms)Expiry; message is discarded or dead-lettered
Delivery delaysetDeliveryDelay(ms)Scheduled delivery (JMS 2.0+)
PropertiessetProperty(name, value)Routing and selector data
Async sendsetAsync(CompletionListener)Higher throughput, callback-based confirmation
Disable ids/timestampssetDisableMessageID(true)Micro-optimisation for very high volume

Consumer

CreationSemantics
createConsumer(queue)Competing consumer on a queue
createConsumer(topic)Non-durable subscription
createDurableConsumer(topic, name)Durable subscription, one active consumer
createSharedConsumer(topic, name)Shared non-durable subscription (scales topics)
createSharedDurableConsumer(topic, name)Shared durable subscription — durability plus scaling
createConsumer(dest, selector)Broker-side filtering (Chapter 3)
Classic JMS compared with JMSContext
Figure 1.2.2 — Classic JMS compared with JMSContext

4· Java / Jakarta EE Code Examples

JAVAConnection, session, producer
// Classic API — still found in older code, and worth being able to read
@Resource(lookup = "java:/ConnectionFactory") ConnectionFactory factory;
@Resource(lookup = "java:/jms/queue/orders") Queue queue;
 
public void sendClassic(String payload) throws JMSException {
    try (Connection connection = factory.createConnection();
         Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
         MessageProducer producer = session.createProducer(queue)) {
 
        TextMessage message = session.createTextMessage(payload);
        message.setStringProperty("region", "EU");
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        producer.send(message);
    }
}
JAVAThe same send with JMSContext
// Simplified API — inject the context and let the container manage it
@Inject
@JMSConnectionFactory("java:/ConnectionFactory")
JMSContext context;
 
@Resource(lookup = "java:/jms/queue/orders") Queue queue;
 
@Transactional
public void send(String payload) {
    context.createProducer()
           .setProperty("region", "EU")
           .setDeliveryMode(DeliveryMode.PERSISTENT)
           // deliver five seconds from now
           .setDeliveryDelay(5_000)
           .send(queue, payload);                        // no checked exception
}
JAVAA transacted session used as a batch reader
// Application-managed context: you control the lifecycle, so you must close it
public List<String> drain(int max) {
    List<String> out = new ArrayList<>();
    try (JMSContext ctx = factory.createContext(JMSContext.SESSION_TRANSACTED)) {
        JMSConsumer consumer = ctx.createConsumer(queue);
        for (int i = 0; i < max; i++) {
            String body = consumer.receiveBody(String.class, 1_000);
            if (body == null) break;
            out.add(body);
        }
        ctx.commit();                                    // acknowledge the batch
    }
    return out;
}
JAVAScaling a topic subscription across instances
// Shared durable subscription: several instances, one logical subscriber
try (JMSContext ctx = factory.createContext()) {
    // not needed for shared subscriptions
    ctx.setClientID(null);
    JMSConsumer c = ctx.createSharedDurableConsumer(ordersEvents, "billing");
    c.setMessageListener(m -> billing.handle(m));
    ctx.start();
}
// Every instance of the billing service joins subscription "billing";
// each message is processed once by the group, and retained while all are offline.
JAVAAsynchronous sends
// Asynchronous send with confirmation — throughput without losing feedback
context.createProducer()
       .setAsync(new CompletionListener() {
           @Override public void onCompletion(Message message) { metrics.sent(); }
           @Override public void onException(Message message, Exception e) {
               outbox.markFailed(message);               // the send did NOT happen
           }
       })
       .send(queue, payload);

Deep Dive — Threading, Pooling and Resource Leaks

ObjectThread-safe?PoolingFailure mode if misused
ConnectionFactoryYesInjected/sharedNone
ConnectionYesPool itBroker connection storm if created per message
Session / JMSContextNoOne per threadInterleaved sends, corrupted state, obscure errors
MessageProducer / JMSProducerFollows its sessionPer sessionSame as session misuse
MessageConsumerFollows its sessionPer sessionLost or duplicated deliveries

Two rules cover almost every defect in this area. First, never store a session or JMSContext in a field of a shared object — inject it, or create it inside the method and close it. Second, never open a connection per message: in Jakarta EE the container's pooled factory handles this, but code copied from standalone examples frequently does not.

JAVAWhat not to do
// The leak that survives code review: a context stored on an application-scoped bean
@ApplicationScoped
public class BadSender {
    // shared across threads — unsafe
    private JMSContext context;
    @PostConstruct void init() { context = factory.createContext(); }
}
 
// Correct: injected (request/transaction-scoped) or created and closed per use
@Inject JMSContext context;

Deep Dive — Connection Loss and Reconnection

ConcernBehaviourWhat to configure
Broker restartConsumers stop receiving; sends failClient reconnect settings on the factory URL
MDB consumersContainer retries activationActivation retry interval and attempts
In-flight messagesUnacknowledged ones are redeliveredIdempotent consumers (Chapter 3)
Failover in a clusterClient moves to the backup nodeHA broker configuration, client failover list
Silent half-open socketsNothing arrives, no errorHeartbeats / connection TTL on both sides

The most dangerous case is the last one: a consumer that appears healthy but receives nothing. Broker-side heartbeats plus an application metric for "messages processed in the last N minutes" detect it; a liveness probe that only checks the HTTP port will not.

5· Configuration, Defaults & Diagnostics

SettingWhereNote
Connection factory URL / pool sizeServer or MicroProfile configSized with consumer concurrency
clientIdConnectionMandatory for unshared durable subscriptions
maxSessionMDB activationConcurrent onMessage invocations per instance
Consumer window / prefetchFactoryLower it when messages are slow to process
setDeliveryDelayProducerScheduled messages without a timer service
Exception listenerConnectionLog and alert on connection loss
ErrorMeaning
JMSRuntimeException: Producer is closedContext used after close — often a stored context
InvalidDestinationExceptionDestination not defined in this environment
InvalidClientIDExceptionTwo instances using the same client id for a durable subscription
ResourceAllocationExceptionPool exhausted — connections not returned
MessageFormatExceptiongetBody(Class) called with the wrong type

6· Production Usage Patterns

  • @Inject JMSContext inside transactional beans; no contexts stored in fields.
  • Container connection pooling, with pool size aligned to MDB concurrency.
  • Shared durable subscriptions for topics consumed by scaled services.
  • Exception listeners and a "messages processed recently" health metric.
  • Destinations defined in infrastructure configuration per environment.

7· Common Pitfalls & Misconceptions

  • Sharing a session or JMSContext across threads.
  • Creating a connection per message, exhausting broker resources.
  • Forgetting connection.start() in the classic API, so nothing is received.
  • Duplicate clientId across instances, which blocks durable subscriptions.
  • Not closing application-managed contexts, leaking sessions and consumers.
  • Large prefetch with slow consumers, so one instance holds messages others could process.

8· Best Practices

  • Prefer JMSContext and let the container manage lifecycle and transactions.
  • Treat sessions as thread-confined objects, always.
  • Configure client identifiers and subscription names deliberately and document them.
  • Monitor connection state and processing rate, not just process liveness.

9· Architect's Perspective & Trade-offs

ChoiceOption AOption BGuidance
API styleClassic (connection/session)JMSContextJMSContext for all new code
ConsumptionMDBListener in application codeMDB — container transactions and pooling
Topic scalingOne durable consumerShared durable subscriptionShared, for scaled services
Send styleSynchronousAsynchronous with listenerSynchronous unless throughput demands otherwise

10· Interview Q&A

Q1L1 · BasicConcept

What does a JMS session do?

A session is the single-threaded context in which messages are produced and consumed. It creates producers, consumers, messages and temporary destinations, and it defines delivery semantics: either an acknowledgement mode such as AUTO_ACKNOWLEDGE or CLIENT_ACKNOWLEDGE, or transacted mode, where sends and receives are grouped, confirmed with commit and undone with rollback. It also provides the ordering guarantee, because messages sent on one session to one destination arrive in the order they were sent. Sessions are cheap compared with connections but must never be shared between threads. In a message-driven bean, session behaviour is decided by the container and its JTA transaction rather than by application code.

Q2L1 · BasicConcept

What is JMSContext?

JMSContext is the simplified API introduced in JMS 2.0 and carried into Jakarta Messaging. It combines a connection and a session in one object, so a single factory.createContext() call or an @Inject replaces creating a connection, a session and a producer separately. It throws the unchecked JMSRuntimeException instead of the checked JMSException, implements AutoCloseable, and offers fluent producers, as in context.createProducer().setDeliveryDelay(5000).send(queue, body). When injected in a Jakarta EE container it is container-managed: it joins the current JTA transaction and is closed automatically at the end of the transaction or request. It is the recommended style for all new code.

Q3L2 · IntermediateTricky

Which JMS objects are thread-safe?

ConnectionFactory, Connection and Destination objects are thread-safe and designed to be shared. Session, JMSContext, and the producers and consumers created from them are not; each must be confined to one thread at a time. The reason is that a session holds ordering, acknowledgement and transaction state, which concurrent use would corrupt. The symptoms are rarely clean exceptions: more often messages are interleaved, acknowledged at the wrong moment or lost under load, which makes the defect hard to reproduce. So never store a session or an application-managed JMSContext in a field of a shared bean. Inject a container-managed JMSContext, or create one inside the method and close it.

Q4L2 · IntermediateConcept

What is a shared durable subscription for?

A shared durable subscription lets several consumers share one durable topic subscription, identified by its name. Before JMS 2.0 a durable subscription allowed only one active consumer, tied to a client identifier, so a service could not scale its consumption of a topic without receiving duplicates. With createSharedDurableConsumer(topic, "billing"), every instance of the billing service joins the same subscription: each message published to the topic is delivered once to the group, load is spread across the instances, and the broker retains messages while all of them are offline. Other services keep their own subscriptions and still receive every message, much like separate Kafka consumer groups.

Q5L3 · Senior EngineerInternals

Why is creating a connection per message a problem?

Because a connection is the expensive object in JMS. Creating one means opening a TCP connection, often with a TLS handshake, authenticating, and allocating broker-side resources and threads, which can take milliseconds and costs far more than the send itself. Doing that per message multiplies latency, burns CPU on both sides and, under load, produces connection storms that exhaust broker limits or file descriptors, destabilising the broker exactly when traffic peaks. The fix is reuse: in Jakarta EE use the container's pooled connection factory, and in standalone code keep a long-lived connection or a pooling factory, creating only the cheap sessions or contexts per unit of work.

Q6L3 · Senior EngineerScenario

How do you detect a consumer that has silently stopped receiving?

Monitor what the consumer achieves, not whether its process is alive. A half-open connection or a stuck listener can leave a consumer looking perfectly healthy while it receives nothing. First, enable heartbeats or a connection TTL on both client and broker, so dead connections are detected and the exception listener or the MDB activation triggers a reconnect. Second, publish an application metric such as messages processed in the last five minutes, and alert when it drops to zero while queue depth or consumer lag is growing. Broker metrics for consumer count per destination help too. A liveness probe that only checks the HTTP port will report such a consumer as healthy.

Q7L4 · Technical ArchitectDesign

How should destinations be provisioned across environments?

Treat destinations as infrastructure, not code. Define queues, topics, dead-letter settings and redelivery policies in the broker configuration, Helm charts or Terraform, versioned with the rest of the environment; reserve deployment-level definitions such as @JMSDestinationDefinition for simple cases. Application code refers to destinations by a logical JNDI name or a configuration property and never creates them at run time from hard-coded physical names. That way the same artefact runs in development, test and production, while each environment uses its own names, limits and security. Automate provisioning, include destinations in environment reviews, and give each one an owner so orphaned queues are noticed and removed.

Q8L5 · Solution ArchitectDesign

What capacity factors do you consider when sizing messaging?

I start from the workload: peak and average producer rates, message size, and how long consumers take per message. Required consumer concurrency is roughly peak rate times processing time, so 500 messages per second at 40 milliseconds needs at least 20 concurrent consumers, plus headroom. For persistent messages, broker disk throughput and fsync latency usually set the ceiling, so I check them early. Then I size connections, sessions and MDB maxSession to that concurrency, tune prefetch so slow consumers do not hoard messages, and plan storage for backlogs during outages. Finally I allow for recovery: after an outage, redelivery and backlog drain can double normal load for a while.

Test your knowledge on this topic →Flashcards from this topic's 8 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.