I know this has been asked million times, but so far it didn't answer the question in my head, I think it's best to understand in code, could someone please verify my thinking:
Stateless bean in client:
public void work(){
bean.work1(); <--- this uses instance 1 in App Server
...
bean.work2(); <--- this can be instance 2 in App Server
}
Stateful bean in client:
public void work(){
bean.add_item(item); <------- this uses instance 1 in App Server
....
bean.checkout(); <------- this uses instance 1 in App Server
}
To destroy a session:
public void work(){
...
bean = null;
}
From Oracle doc
As its name suggests, a session bean is similar to an interactive session. A session bean is not shared; it can have only one client, in the same way that an interactive session can have only one user. When the client terminates, its session bean appears to terminate and is no longer associated with the client.
The state is retained for the duration of the client/bean session. If the client removes the bean, the session ends and the state disappears. This transient nature of the state is not a problem, however, because when the conversation between the client and the bean ends, there is no need to retain the state
If above is correct, my derived question from this is, when the bean reference is set to null, does the App server trash the stateful bean instance and create new ones? I am asking this is because:
flush
method, but I don't think that's the right way.this.items
inside the bean, I cannot think of a better reason why to use Stateful bean?Your analysis of which bean instances can be used for stateless/stateful session beans is correct.
Setting the field to null doesn't really do anything. To destroy the stateful session bean, you need to invoke a remove method (if you're using EJB 3, that means invoking a method annotated @Remove
).
If you're referring to a stateless session bean, you shouldn't store state in the bean at all. If you're referring to a stateful session bean, a flush method seems plausible, or you could put the logic in the @Remove
method (perhaps named flush).
Altering the state is fine. You're right that keeping state is the intent of a stateful session bean.
Yes, but it also means the association with the client. A stateless session bean can clearly store state in member variables, but since a client is not guaranteed to get the same instance, the EJB (not the instance) has no real state. That also means stateless session beans should not store client state in member variables because there is no real use.