That is the error you get if you are trying to access the same instance of a stateful session bean (SSB) with more than one thread.
Our reference to the stateful session bean is stored in the HttpSession object and passed to a stateless session facade. In our scenario the error occurs because we are using framesets in the web tier and up to three threads may be trying to access our SSB at once.
When the header and middle part of a web page request information from the SSB via the session facade, the container will then make three instances of the session facade available to serve each call but each of these instances is trying to access the same instance of the stateful session bean.
A quick search on Google (as always) showed this is a common problem but I was not able to find a quick solution. One of my colleagues suggested that I should try “synchronization” which I did with what seems until now a success.
In my session facade bean, I surround all accesses to the stateful session bean with synchronization blocks, locking on the SSB. This will prevent more than one thread accessing the SSB; once a thread has entered the SSB any additional threads will be queued.
public void submitText(TextTo text, TextSessionLocal textLocal) {
log.debug("ENTER submitText(TextTo text, TextSessionLocal textLocal): "+text);
synchronized (textLocal) {
//set message data in SSB
textLocal.setMsgTitle(text.getMsgTitle());
.... more code
}
log.debug("EXIT submitText(TextTo text, TextSessionLocal textLocal));
}
One might ask what impact this may have on the performance. Because it will only be one single user that will be accessing the same instance of a SSB I don’t think the performance will be detoriated by much but later stress testing will show more.
Stateful session beans should be avoided if possible. Especially if purpose of it is for storing some HttpSession data, like intermediate steps in a shopping process. It is recommended then to store the partial information in the HttpSession and as a last step to use a stateless session bean to perform the business logic. Well, maybe next time 😉
Update 05/11/03
This QA about EJBs article from Sun is very related