Q

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)?
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

Dig deeper on Java Web Services

Pro+

Features

Enjoy the benefits of Pro+ membership, learn more and join.

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

0 comments

Oldest 

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:

-ADS BY GOOGLE

SearchSoftwareQuality

SearchCloudApplications

SearchAWS

TheServerSide

SearchWinDevelopment

Close