2 Replies Latest reply on Nov 7, 2005 3:44 PM by adrian.brock

    Clarification on multiple threads and sessions

    timfox

      The JMS spec says that sessions are essentially a single threaded construct, with the exception of the close() method which can be called by a different thread than the "controlling" thread. (spec 4.4.1)

      In the following example:



      Connection conn = ...
      conn.start();
      Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageConsumer cons = sess.createConsumer(queue);

      MessageListener listener = new MyMessageListener(sess);
      cons.setMessageListener(listener);

      MessageProducer prod = sess.createProducer(queue);
      prod.send(sess.createMessage);

      //do something with the session (not close though)
      sess.recover(); //is this legal?


      class MyMessageListener implements MessageListener
      {

      Session sess;

      int count;

      MyMessageListener(Session sess)
      {
      this.sess = sess;
      }


      public void onMessage(Message m)
      {
      count++;

      //do something with the session
      if (count == 0) sess.recover();

      }
      }



      In the above example we start a message listener, then send a message, then in the thread that sent the message we do something with the session (session.recover()).

      This could result in session.recover() being executed concurrently from the message listener thread and the thread that set the message listener, which seems to contravene the spec.

      Is the above code illegal JMS client code?

      If so, should we throw exceptions to the user if they attempt to do anything with a session (other than close()) after a message listener has been set on one of it's consumers?

        • 1. Re: Clarification on multiple threads and sessions
          timfox

          Ignore me.
          I've found the part of the spec that deals with this (4.4.6)

          :)

          • 2. Re: Clarification on multiple threads and sessions

            To give the answer (although this is an FAQ :-)

            "timfox" wrote:

            Is the above code illegal JMS client code?


            NO.


            If so, should we throw exceptions to the user if they attempt to do anything with a session (other than close()) after a message listener has been set on one of it's consumers?


            In some places it should throw an exception. e.g. trying to receive on a consumer
            that has a message listener.

            In general, the session is not thread safe and it is "caveat emptor".
            If the user does not use it correctly it should not break the jms server.
            It will almost certainly break their application, e.g. acknowledging unprocessed
            messages or vice versa.