2 Replies Latest reply on Jul 20, 2005 12:50 AM by bloodasp

    MDB Accessing datasource

    bloodasp

      Hi,

      I have a question regarding MDBs accessing a datasource. Since application servers create a pool of MDBs that will consume messages, how should the datasource be retrieved efficiently?

      public class MDB implements MessageDrivenBean, MessageListener
      {
       private MessageDrivenContext context = null;
       private DataSource dataSource = null;
      
       public void ejbCreate()
       {
       InitialContext initialContext = new InitialContext();
       dataSource = (DataSource) initialContext.
       lookup(lookupstring);
       }
      
       public void setMessageDrivenContext(MessageDrivenContext context)
       {
       context = context;
       }
      
       public void onMessage(Message msg)
       {
       Connection connection = dataSource.getConnection();
       ...
       }
      
       public void ejbRemove()
       {
       }
      }
      


      Since the application server will instantiate a pool of MDBs, the ejbCreate method will be called n times depending on the size of the MDB pool. Each instance of the MDB will have their own instance of the datasource. I want my MDBs to share a single instance of the datasource. How can I do this?

      For example, fo servlets, you have an init method which is only called once by the servlet container where you can instantiate a datasource. Subsequent requests to the servlet will create 1 thread for each request. But each thread will only access a single instance of the datasource.

      How can i do this with MDBs? Is my code correct or is there a better way? Or is it even a non-issue for application servers.

      Can anyone point to any reading about this or can clarify this?

      Thanks in advance :)


        • 1. Re: MDB Accessing datasource
          genman

           

          I want my MDBs to share a single instance of the datasource.


          It does, if you're getting it from JNDI. They're the same object.

          Note that since connections from the datasources are pooled, even if you have multiple datasource member variables, your application may only need one or two physical connections. I wouldn't worry about it. Your code is correct. Just be sure to always close your connection when done.

          • 2. Re: MDB Accessing datasource
            bloodasp

            Thanks a lot. Off to coding :D