On this page
- 1. · Concept & Definition
- 2. · Why It Matters
- 3. · How It Works
- 4. · Java / Jakarta EE Code Examples
- Deep Dive — Threading, Pooling and Resource Leaks
- Deep Dive — Connection Loss and Reconnection
- 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
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.

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
| Aspect | Detail |
|---|---|
| Created from | ConnectionFactory (injected, or JNDI lookup) |
| Cost | A TCP connection plus authentication — pool it, never create per message |
| State | Must be start()ed before consumers receive; producers may send before |
| Client identifier | Required for durable subscriptions: identifies the client across restarts |
| Exception listener | setExceptionListener reports connection loss asynchronously |
| Thread safety | The 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 mode | Meaning |
|---|---|
AUTO_ACKNOWLEDGE | Acknowledged when onMessage returns or receive completes |
DUPS_OK_ACKNOWLEDGE | Lazy batched acknowledgement; duplicates possible |
CLIENT_ACKNOWLEDGE | Application calls acknowledge(), confirming all prior messages |
SESSION_TRANSACTED | commit() / rollback() on the session |
| Container-managed | In 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
| Setting | API | Effect |
|---|---|---|
| Delivery mode | setDeliveryMode(PERSISTENT / NON_PERSISTENT) | Whether the broker writes it to disk |
| Priority | setPriority(0–9) | Best-effort ordering hint; support varies |
| Time to live | setTimeToLive(ms) | Expiry; message is discarded or dead-lettered |
| Delivery delay | setDeliveryDelay(ms) | Scheduled delivery (JMS 2.0+) |
| Properties | setProperty(name, value) | Routing and selector data |
| Async send | setAsync(CompletionListener) | Higher throughput, callback-based confirmation |
| Disable ids/timestamps | setDisableMessageID(true) | Micro-optimisation for very high volume |
Consumer
| Creation | Semantics |
|---|---|
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) |

4· Java / Jakarta EE Code Examples
// 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);
}
}// 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
}// 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;
}// 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.// 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
| Object | Thread-safe? | Pooling | Failure mode if misused |
|---|---|---|---|
ConnectionFactory | Yes | Injected/shared | None |
Connection | Yes | Pool it | Broker connection storm if created per message |
Session / JMSContext | No | One per thread | Interleaved sends, corrupted state, obscure errors |
MessageProducer / JMSProducer | Follows its session | Per session | Same as session misuse |
MessageConsumer | Follows its session | Per session | Lost 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.
// 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
| Concern | Behaviour | What to configure |
|---|---|---|
| Broker restart | Consumers stop receiving; sends fail | Client reconnect settings on the factory URL |
| MDB consumers | Container retries activation | Activation retry interval and attempts |
| In-flight messages | Unacknowledged ones are redelivered | Idempotent consumers (Chapter 3) |
| Failover in a cluster | Client moves to the backup node | HA broker configuration, client failover list |
| Silent half-open sockets | Nothing arrives, no error | Heartbeats / 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
| Setting | Where | Note |
|---|---|---|
| Connection factory URL / pool size | Server or MicroProfile config | Sized with consumer concurrency |
clientId | Connection | Mandatory for unshared durable subscriptions |
maxSession | MDB activation | Concurrent onMessage invocations per instance |
| Consumer window / prefetch | Factory | Lower it when messages are slow to process |
setDeliveryDelay | Producer | Scheduled messages without a timer service |
| Exception listener | Connection | Log and alert on connection loss |
| Error | Meaning |
|---|---|
JMSRuntimeException: Producer is closed | Context used after close — often a stored context |
InvalidDestinationException | Destination not defined in this environment |
InvalidClientIDException | Two instances using the same client id for a durable subscription |
ResourceAllocationException | Pool exhausted — connections not returned |
MessageFormatException | getBody(Class) called with the wrong type |
6· Production Usage Patterns
@Inject JMSContextinside 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
JMSContextacross threads. - Creating a connection per message, exhausting broker resources.
- Forgetting
connection.start()in the classic API, so nothing is received. - Duplicate
clientIdacross 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
JMSContextand 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
| Choice | Option A | Option B | Guidance |
|---|---|---|---|
| API style | Classic (connection/session) | JMSContext | JMSContext for all new code |
| Consumption | MDB | Listener in application code | MDB — container transactions and pooling |
| Topic scaling | One durable consumer | Shared durable subscription | Shared, for scaled services |
| Send style | Synchronous | Asynchronous with listener | Synchronous unless throughput demands otherwise |
10· Interview Q&A
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.
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.
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.
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.
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.
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.
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.
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.