0

Please look at this snippet:

@Stateless 
public class A {
   @EJB
   B b; // B is stateful EJB

   b.init(); // initialize Sets and List that are used in doSthInB(C c)
   public void doSthInA(){
        for(C c){
           b.doSthInB(c); // doSthInB use REQUIRES_NEW transaction type
        }
   }
}

My intention is to process a collection of objects of type C. The method doSthInB modifies entities and the result should be persisted at the end of the method call (that is why I user REQUIRES_NEW). When during processing of some element from the input collection some error occurs then only this operation should not be persisted, it should be logged and the processing of other elements should not be stopped.

What I get during processing is:javax.ejb.EJBException: java.lang.IllegalStateException: Bean is associated with a different unfinished transaction

Maybe my idea is wrong. Any tips?

Marcin Sanecki
  • 1,324
  • 3
  • 19
  • 35
  • ok guys, I changed Stateful to Stateless. Now I get interesting exception NPE. It seems that for some iteration collections which I initialize in b.init() are not instantiated. I iterate over hundreds of objects in the for loop and I suppose that ejb container use more than one ejb to process every single call to b.doSthInB(c). But only for the first one ejb the b.init() is called and that is why I get NPE. Am I right? – Marcin Sanecki Feb 05 '14 at 10:05

1 Answers1

2

I see that you are injecting a Stateful in a Stateless bean. Despite the fact that this is allowed by the specification in the most cases this is an error.

I don't know if you are completely aware of what this design decision implies. If not try to avoid to use this approach. I think that this probably be the cause of your exception.

Gabriel Aramburu
  • 2,951
  • 2
  • 16
  • 20
  • Interesting, I wasn't aware of any design flaw there. Even in a stateless bean, when the code is running it is locked to a single thread that took it from the pool so I wouldn't see why there is an issue with injecting a stateful, thread-bound bean into a stateless EJB. Unless there are issues with transaction boundaries as this thread seems to imply. Do you know of any good reading material on this subject? – Gimby Feb 04 '14 at 11:53
  • 2
    I first realized of this issue when reading [EJB 3.1 in action](http://refcardz.dzone.com/refcardz/dependency-injection-in-ejb3); about the exception the [ejb 3.1 specification](https://jcp.org/aboutJava/communityprocess/final/jsr318/) could help. Also [here](http://stackoverflow.com/questions/9384368/access-existing-instance-stateful-inside-stateless-java-ee-6?answertab=votes#tab-top) there is a good related answer. – Gabriel Aramburu Feb 04 '14 at 16:05
  • I'll give that book a read then, of all the books I have read on EJB tech this particular tidbit has not passed the review just yet. – Gimby Feb 05 '14 at 08:31