Difference between Stateless and Stateful session bean

ejb-3.0

I knew stateful beans maintain conversational session between different instance method call,but stateless will not.My question,assume I have a stateless bean implementation like below

import javax.ejb.Stateful;
import javax.ejb.Stateless;

import com.tata.ejb3.data.HelloEJBInterface;

@Stateless
public class ValueEJB implements ValueEJBInterface{

    private int value;
    @Override
    public int getValue() {
        return this.value;
    }

    @Override
    public void setValue(int value) {
        this.value = value;
    }
}

I have my bean client(A servlet) which initiates bean invocation as below

@EJB(mappedName="E/ValueEJB /remote")
ValueEJBInterface value;

....

value.setValue(250);
System.out.println(value.getValue());//This statement prints the value 250

....

According to my understanding as my bean is stateless bean it should not displayed with value 250.

private int value; is an instant variable,if one stateless method set its value , the value will be expired on method exit.But here, I am able to get the value '250' even via my second method call. Is it a violation of stateless concept? Am I lacking something?

Best Answer

Difference between Stateful v Stateless bean behavior when calling different methods.


STATEFUL: When calling different methods on a Stateful Bean, different bean instances are created.

((MyStatefulBeanRemote) ctx.lookup("ejb/MyStatefulBean")).doingStatefulThing();

((MyStatefulBeanRemote) ctx.lookup("ejb/MyStatefulBean")).doingNothingStatefulThing();

***Output: Note the creation of separate objects.***

INFO: Calling doingStatefulThing...com.myeclipseide.ejb3.stateful.**MyStatefulBean@2fe395**

INFO: Calling doingNothingStatefulThing...com.myeclipseide.ejb3.stateful.**MyStatefulBean@81cfcb**

STATELESS: When calling different methods on a Stateless Bean, the beans are pooled, hence no new instances of the bean are created.

((MyStatelessBeanRemote) ctx.lookup("ejb/MyStatelessBean")).doSomething(); 

((MyStatelessBeanRemote) ctx.lookup("ejb/MyStatelessBean")).doNothing();

***Output: Note the reuse of he bean object.***

INFO: Doing something ...com.myeclipseide.ejb3.stateless.**MyBean@213b61**

INFO: Doing Nothing ...com.myeclipseide.ejb3.stateless.**MyBean@213b61**
Related Topic