cancel
Showing results for 
Search instead for 
Did you mean: 

Question about Stateless vs. Statefull Bean

Former Member
0 Kudos

In my opnion a stateless session bean should not save its state.

I have a stateless bean with this contents:


private int r = 0;
public int Count() { return(++r); }

I have a JUnit test which creates that bean from its setUp function and this test function:


public void testCount() throws RemoteException {
  assertEquals("bean cannot count (1st)", 1, bean.Count());
  assertEquals("bean cannot count (2nd)", 1, bean.Count());
}

The second assert fails because the return value is 2.

So it obviously preserves its state between the two method calls.

Do I misunderstand the meaning of 'stateless'???

Accepted Solutions (1)

Accepted Solutions (1)

Former Member
0 Kudos

>>>>Do I misunderstand the meaning of 'stateless'???

well..unfortunately YES.In a way, you have not done anything which is syntactically / programatically wrong, but what you have done is Conceptually wrong.

When you say stateless, the state is to be considered between method calls. Meaning, the bean should not maintain its state across method calls. Imagine a stateless session bean which responds to transaction calls from an ATM machine and maintains the balance of customer across method calls...BLUNDER..ain't it?

In simple terms, stateless session beans should not have class variables.

<b>private int r = 0;</b>

r should ideally be a local variable for the method count whatever may be the functionality, as stateless beans need not conserve the state from client to client, if you end up doing so,defeats the whole concept!!!

Former Member
0 Kudos

Hmm.... so it is only a conceptual difference.. that seems to be my misunderstanding.

If I really want to have this functionality (counting with memory) I 've done nothing wrong - the Unit tests are proving that.

Anyway, thanks for the explanation.

Answers (1)

Answers (1)

Former Member
0 Kudos

Hi,

normally those StatelessBeans are in a big BeanPool and your Container decides which bean will be used, when you call a SessionBean-Method.

Now, you can be lucky and the container decides to take the very same instance of the bean when you call the method for the second time. The more clients use those beans the less likely it is that you receive the same instance. And than you will get funny results if you rely on the state of the instance variable.

Even if you call twice bean.Count() directly one after the other - that doesn't mean the instance of 'bean' is the same in both cases (like you would expect it from any other Plain Old Java Object.) That's EJB. Allocation of Bean-Instances is his decision only.

Best Regards, Astrid

Former Member
0 Kudos

Clear!

I'll change my way of using stateless beans.