Search code examples
jms

What does improper use of a JMS session look like?


My understanding is that JMS sessions are not deemed thread-safe, so therefore you should not access shared resources by the session. Does this mean that creating message consumers/producers need to happen within a synchronized context? And/or are there more subtle synchronizations to keep in mind when having multiple consumers/producers on a session?


Solution

  • Improper use of a JMS Session, at least in terms of concurrency, looks like multiple threads using the Session simultaneously. Here's what the JavaDoc for Session says in regards to thread safety:

    A Session object is a single-threaded context for producing and consuming messages. Although it may allocate provider resources outside the Java virtual machine (JVM), it is considered a lightweight JMS object.

    ...

    One typical use is to have a thread block on a synchronous MessageConsumer until a message arrives. The thread may then use one or more of the Session's MessageProducers.

    If a client desires to have one thread produce messages while others consume them, the client should use a separate session for its producing thread.

    Once a connection has been started, any session with one or more registered message listeners is dedicated to the thread of control that delivers messages to it. It is erroneous for client code to use this session or any of its constituent objects from another thread of control. The only exception to this rule is the use of the session or message consumer close method.

    It should be easy for most clients to partition their work naturally into sessions. This model allows clients to start simply and incrementally add message processing complexity as their need for concurrency grows.

    The close method is the only session method that can be called while some other session method is being executed in another thread.

    In short, the recommendation is to have a Session per-thread since a Session is designed to be "lightweight."

    However, if you do wish to use a Session from multiple threads then you must ensure that those uses are protected via some concurrency control (e.g. synchronized method or code block).