Java Message Service (JMS) is the standard Java API for messaging. It defines a common interface for creating, sending, and receiving messages, independent of the underlying provider.

Messaging Domains

Domain Model Use case
Point-to-Point (P2P) Queue, one consumer Task distribution
Publish/Subscribe (Pub/Sub) Topic, multiple subscribers Event broadcasting

Core API

Interface Role
ConnectionFactory Creates connections
Connection Client connection to provider
Session Single-threaded context for producing/consuming
MessageProducer Sends messages
MessageConsumer Receives messages
Destination Queue or Topic target

JMS 2.0 Simplified API

  ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");

try (JMSContext context = factory.createContext()) {
    Queue queue = context.createQueue("orders");

    // Send
    context.createProducer().send(queue, "Order #12345");

    // Receive
    String message = context.createConsumer(queue).receiveBody(String.class, 5000);
}
  

Message Types

Type Content
TextMessage String
BytesMessage byte[]
ObjectMessage Serializable object
MapMessage Key-value pairs
StreamMessage Stream of Java primitives

Delivery Modes

  // Persistent — survives broker restart
producer.setDeliveryMode(DeliveryMode.PERSISTENT);

// Non-persistent — faster, may lose messages
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
  

Acknowledgment Modes

Mode Behavior
AUTO_ACKNOWLEDGE Ack on receive
CLIENT_ACKNOWLEDGE Explicit ack
DUPS_OK_ACKNOWLEDGE Lazy ack, duplicates possible
SESSION_TRANSACTED Batch ack via commit

JMS Providers

Provider Type
ActiveMQ / Artemis Open source
IBM MQ Enterprise
Amazon SQS (via JMS) Cloud
RabbitMQ (via JMS plugin) AMQP with JMS API

JMS vs Modern Alternatives

Feature JMS Kafka RabbitMQ
Standard Java standard Apache project AMQP protocol
Message retention Consumed = deleted Configurable log Queue-based
Replay No Yes Limited
Throughput Moderate Very high High
Spring support Spring JMS Spring Kafka Spring AMQP

Best Practices

  • Use JMS 2.0 simplified API (JMSContext) over JMS 1.1 verbose API
  • Prefer persistent delivery for business-critical messages
  • Use CLIENT_ACKNOWLEDGE for reliable processing
  • Consider Kafka or RabbitMQ for new projects — JMS is declining in new development
  • Use Spring JMS for integration with @JmsListener