Instance variable in Stateless Session Bean


EJB programming & troubleshooting: Instance variable in Stateless Session Bean

  1. Instance variable in Stateless Session Bean (3 messages)

    Hello Experts,
    Under what circumstances we can have instance variable in Stateless Session Bean.
  2. Instance variable in Stateless Session Bean[ Go to top ]

    You can use instance variables in Stateless Session Beans provided that:

    a) The instance variable's value does not change, e.g. is it initialized in the constructor, setSessionContext() or ejbCreate().

    b) The instance variable is only used for the invocation of a single public business method:

    public void businessMethod() {
      this.var = // ... initialize variable
      // Call other, private methods
      this.var = null; // Discard variable value

    Of the two, (a) is safe and (b) is risky, not to mention unnecessary (the variable value can be passed as a method parameter instead).
  3. Hi

    When we have any class level instance variable in stateless session bean, what will happen to that variable, will it be cleaned by container or not ?

    Pardeep Sharma
  4. Under the circumstance that you don't care what the value is, unless the variable is initialized once and onle once and does not change after that.

    Multiple client invocations on the same remote interface are in no way gauranteed to invoke the same bean instance on the server. This is not a rule, it's just the nature of stateless beans. If your client needs to somehow maintain that specific variable value, or, needs the value to support any type of conversational state, then you're better off using a stateful bean.