Wednesday, July 13, 2011

life cycle of a message-driven bean.

The life cycle of a message-driven bean has two states, namely the ‘does not exist’ and ‘pooled’ state. A message-driven bean does not maintain any client specific state. It does not have the home and component interfaces. The following image shows the life cycle of a message-driven bean:

 

lifemdb

The container is responsible for maintaining the life cycle of a message-driven bean. A bean moves from the ‘does not exist’ to the ‘method ready’ state using the following methods:

  • The container creates a bean instance by calling the newInstance() method on a class.
  • The container assigns a context to the bean by invoking the setMessageDrivenContext() method.
  • The container calls the ejbCreate() method. The initialization code should be written in this method.

The bean instance in the pooled state can perform operations using the onMessage() method. The container ensures that only one thread executes at a particular moment. The message -driven beans connect to the JMS server, consume messages from the server, and process those messages.

The bean instance can be removed by the container by calling the ejbRemove() method. By calling this method, the container moves the bean instance back to the ‘does not exist’ state.

Creating Object using keyword “new” & method “newInstance()”

When u use the new operator to create an instance of a class, u cant change the class which is been instantiated. In other words, the class which is instantiated is determined at compile time.


If you use class.newInstance(), then u can change the class which is been instantiated at runtime. In other words for example

Class c = Class.forName("Some class Name");
Object o = c.newInstance();

Here, you can change the String argument in the class.forName() method and change the class which is getting instantiated. Say u got this String from a property file, then u don't even have to compile the class in order to get another different class instantiated.

   1:  package test;
   2:  class Emp {
   3:      String name;
   4:      public String getName() {
   5:          return name;
   6:      }
   7:      public void setName(String name) {
   8:          this.name = name;
   9:      }
  10:  }
  11:  public class Instance {
  12:      public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
  13:          Class c;
  14:          c = Class.forName("test.Emp");
  15:          Emp e = (Emp) c.newInstance();
  16:          Emp emp = Emp.class.newInstance();
  17:          e.setName("Ramesh");
  18:          emp.setName("Krishna");
  19:          System.out.println(e.getName());
  20:          System.out.println(emp.getName());
  21:      }
  22:  }