Ask the Expert

Asynchronous business method on a session bean w/out MDB

Is there any way to call a business method on a session bean (Stateless) in an asynchronous manner (without using a MDB)?

    Requires Free Membership to View

You can create your own asynchronous, JMS-enabled, message listener/receiver and make calls to the session bean from its onMessage callback, as in the following example:
import javax.jms.*;

public class MyAsyncReceiver
{
  public MyAsyncReceiver()
  {
    String queueName = "myqueue";

    try {
      Context jndiContext = new InitialContext();
      QueueConnectionFactory queueConnectionFactory =
         (QueueConnectionFactory)
            jndiContext.lookup("QueueConnectionFactory");
      QueueConnection queueConnection =
         queueConnectionFactory.createQueueConnection();
      QueueSession queueSession =
         queueConnection.createQueueSession(false,
                               Session.AUTO_ACKNOWLEDGE);
      Queue queue = (Queue)jndiContext.lookup(queueName);
      QueueReceiver queueReceiver =
         queueSession.createReceiver(queue);
      queueReceiver.setMessageListener(new MyMsgListener());

      queueConnection.start();

      // wait code should be inserted here
    } catch (JMSException e) {
      System.err.println("Exception: " + e.toString());
    } finally {
      if (queueConnection != null) {
        try {
          queueConnection.close();
        } catch (JMSException e) {
           System.err.println("Exception: " + e.toString());
        }
      }
    }
  }
}

class MyMsgListener implements MessageListener
{
  private MyEJB myEJB = null;

  public void onMessage(Message message)
  {
     System.out.println("Message received");
     callEJB();
  }

  private void callEJB()
  {
     try {
        if (myEJB == null) {
           Context initial = new InitialContext();
           Object objref =
              initial.lookup("java:comp/env/ejb/MyEJB");
           MyEJBHome home =
              (MyEJBHome)PortableRemoteObject.narrow(objref,
                                           MyEJBHome.class);
           myEJB = home.create();
        }
        // Call the EJB's business method
        myEJB.retrieveMessage();
     } catch (Exception e) {
        System.err.println("Exception: " + e.toString());
     }
  }
}

This was first published in November 2003

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: