@Stateless(name="stateless") @Local(Session.class) public class StatelessSessionBean implements Session { private int result; @Override public void add() { result++; } @Override public int get() { return result; } } @Stateful(name="stateful") @Local(Session.class) public class StatefulSessionBean implements Session { private int result; @Override public void add() { result++; } @Override public int get() { return result; } }
Write a servlet to test.
public class StatelessStatefulServlet extends HttpServlet { @EJB(beanName="stateless") private Session stateless1; @EJB(beanName="stateless") private Session stateless2; @EJB(beanName="stateful") private Session stateful1; @EJB(beanName="stateful") private Session stateful2; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { stateless1.add(); System.out.println("Stateless1 result="+stateless1.get()); stateless2.add(); System.out.println("Stateless2 result="+stateless2.get()); stateful1.add(); System.out.println("Stateful1 result="+stateful1.get()); stateful2.add(); System.out.println("Stateful2 result="+stateful2.get()); } }
Output:
[18/08/11 11:49:22:828 EST] 0000001b SystemOut O Stateless1 result=1
[18/08/11 11:49:22:828 EST] 0000001b SystemOut O Stateless2 result=2
[18/08/11 11:49:22:828 EST] 0000001b SystemOut O Stateful1 result=1
[18/08/11 11:49:22:828 EST] 0000001b SystemOut O Stateful2 result=1
In this case, the same stateless session bean instance is used for both stateless1 and stateless2. The result is not predicable. Next time the output could be:
[18/08/11 11:49:22:828 EST] 0000001b SystemOut O Stateless1 result=1
[18/08/11 11:49:22:828 EST] 0000001b SystemOut O Stateless2 result=1
In this case, two different stateless session bean instances are picked up from the instance pool.
But the output for stateful session bean is always stable. Two different stateful session bean instances are always created.