Stateless beans don't preserve state, but there is nothing stopping you from using instance variables to actually preserve it. What you must be aware of, though, is that the next time the same client calls the stateless bean, a completely different instance might be used, and reading the state would yield different results. It is a coincidence (more or less) that your client got the same bean both times. If you want to test it, you can do what I did:
1. create a stateless session bean, with an integer
2. create a servlet that increments the counter, and then retrieves it and displays on screen
3. test it, by going to the url of your servlet, and hold F5 for a few second, maybe more
What I got was that for the first 80-100 invocations the counter kept incrementing, then suddenly it reset itself to 1, and started incrementing again. That's exactly how a stateless bean behaves - the second sequence of calls was to another instance of the same bean type, with the state _not_ preserved.
So, while for such simple test it might act as if stateless beans preserve state and are no different than statefull, consider a scenario where thousands of clients call the same bean (actually there will probably be many instances in a bean pool) - you would notice data inconsistency sooner thatn you might expect!
Also, stateless beans don't have a @Remove method, they cannot be explicitly removed by the client, only by server crash, exception, or inactivity when the container wants to get rid lingering instances.
PS I used Glassfish v2 for my test, but the behavior would be very similar if not almost identical for others.
posted 9 years ago
Sorry for taking so long to reply - I really did appreciate your response - I was just keen to try this out for myself and finding time took longer than ideal!
I did manage to prove what you said. I did this by having threads that would set values on the bean instance then retrieve and compare them.
On JBoss, with stateless I got upto about 2 threads running before they started retrieving values they didn't expect, however a single thread worked fine (but more out of coincidence).
With stateful, I got up to 60+ threads before my system started hanging!
See below for the code used. I've put it here in the hope that it may be useful for someone else (although there are 1 or 2 hacks in there so I wont be adding it to my CV )