I am trying to put out a very simple example of Stateful vs Stateless EJB, and I am getting a very unexpected behavior : As you can see below, stateful beans seem to be instantiated every time, while stateless beans seem to be called through one single instance.
While this makes sense, somehow, it is the exact contrary of what the EJB book I am reading is stating, so I am really stunned.
From my basic understanding, Stateless EJB's are used to perform simple memoryless queries (such as computation for example), while stateful EJB's need to maintain a "state" throughout the client requests (such as an online ecommerce basket).
What confuses me is the instanciation mode, as somehow the "count" integer seems to be kept track of in the stateless beans. Which is not a problem per se, as this bean does -in theory- not need to be re-instanciated at every call, as it is performing a memoryless task, unlike the stateful bean. However, the book I am reading ("EJB 3 Web development through examples", by Celinio Fernandes, for the record) seems to state the opposite when it come to instanciation : "One single Stateful bean instance is created for all calls from a Client, whereas a different Stateless instance is called for every Client Call."
Is that really so? What am I missing here ? This statement in the book does not seem to match my understanding through the code below.
HelloStatelessEJBRemote lbean0 = doLookup1();
HelloStatelessEJBRemote lbean1 = doLookup1();
HelloStatelessEJBRemote lbean2 = doLookup1();
System.out.println(lbean0.sayHello());
System.out.println(lbean1.sayHello());
System.out.println(lbean2.sayHello());
HelloStatefulEJBRemote fbean0 = doLookup2();
HelloStatefulEJBRemote fbean1 = doLookup2();
HelloStatefulEJBRemote fbean2 = doLookup2();
System.out.println(fbean0.sayHello());
System.out.println(fbean1.sayHello());
System.out.println(fbean2.sayHello());
Console Output :
Hello Stateless World n° 0 !!!
Hello Stateless World n° 1 !!!
Hello Stateless World n° 2 !!!
Hello Stateful World n° 0 !!!
Hello Stateful World n° 0 !!!
Hello Stateful World n° 0 !!!
StatelessEJB Code :
@Stateless
@LocalBean
public class HelloStatelessEJB implements HelloStatelessEJB Remote {
int count = 0;
@Override
public String sayHello() {
return "Hello Stateless World n° " + count++ + " !!!";
}
}
StatefulEJB Code :
@Stateful
@LocalBean
public class HelloStatefulEJB implements HelloStatefulEJB Remote {
int count = 0;
@Override
public String sayHello() {
return "Hello Stateful World n° " + count++ + " !!!";
}
}