Reputation: 2767
I still don't understand clearly the difference of stateless and stateful beans in EJB. In which situation should I use stateless and in which stateful?
Upvotes: 1
Views: 2209
Reputation: 685
I will give you good example:
Say there are n no. of users (say clients) Now there is a bean which just takes the country name as input and provides the currency of that country. In this case a bean can be used for n no. of users (clients). It does not make any sense creating individual bean for each client request. So there could be such a bean which can be served to multiple clients and such bean is known as stateless bean. After a stateless bean served a client, it does not destroy but goes to bean pool, so it can serve to other clients.
Now let's take an another example,
In a shopping cart, there is a bean which can contain list of items. So say when you are adding the items while online shopping, the items will be maintained in a single bean which is exclusively created for you. Its life time will be till you finish the shopping. So if I start shopping online, for me another bean will be created. So the reason it is said stateful because it's state remains active though out the whole session i.e. from you start adding the first item till you add n no. of items into the cart and place the final order.
Stateless bean: A bean can serve to multiple clients (any changes by one client would be reflected to other client). Once a stateless bean is no use, it doesn't destroy, rather it goes to bean pool, so in future it can serve to other clients.
Stateful Bean: One bean only for one client. (Any changes by one client will be only for that client as there is no use of this bean for other clients). So once it's service is over, it's getting destroyed.
Upvotes: 3
Reputation: 9162
If you need to maintain a state of the client between the invocations you should use guess what? Right, stateful beans. If you do not care about the state - stateless bean is the right choice.
Upvotes: 1