2

I have read that @Stateful bean (SFSB) should be never injected into @Stateless bean (SLSB). But what is the correct way to achieve the following?

@Stateless
public class FirstEJB
{
    @EJB
    private SecondEJB second;

    public void businessMethod()
    {
        second.businessMethod1();
        second.businessMethod2();
    }
}

There is some state that should be persisted between second.businessMethod1() and second.businessMethod2(), so SecondEJB can't be stateless. There is also no easy way to merge businessMethod1() and businessMethod2() methods into single one, because SecondEJB can have more than 2 business methods and they can be called in defferent combinations.

Actually I have tried to make SecondEJB stateful and it seems to work, but it leads to memory leak. There is no SecondEJB methods marked with @Remove annotation, but I have tried @StatefulTimeout with no luck: a lot of SecondEJB instances created and not removed. Can someone explain why it leaks?

Community
  • 1
  • 1

1 Answers1

0

Just don't use injection. You can use JNDI lookup of the bean at the moment your buisnessMethod is called and SecondEJB instance will be method scoped variable instantiated on every method call.

Stanislav
  • 27,441
  • 9
  • 87
  • 82
  • Thanks. But I still don't understand why using injection leads to memory leak: accordingly to memory analyzer I have very few instances of `FirstEJB` (pooled?) and a lot of `SecondEJB` even if explicitly setting `@StatefulTimeout`. – Anton Batylin Oct 08 '15 at 09:05
  • Are you really sure, it's a memory leak, not just a gc behaviour? I can't see in that easy example anything that could lead to creation of large number of sfsb. The reason is not to use injection of sfsb into slsb is the fact that slsb are pooled and reused, while injection happens only once and you can get already passivated sfsb or with unexpected state. So, the number of sfsb will be the same as the number of slsb or a little greater if slsb was not pooled for some reason. – Stanislav Oct 08 '15 at 09:17
  • Or may be your sfsb are just passivated and waiting to be garbage collected. It's not easy to tell, when should the bean be really garbage collected. And is it because the sfsb, but not because of some other code, that uses the same sfsb at the same time. – Stanislav Oct 08 '15 at 09:26
  • Code in the post is a very simplified version of my real project. And it definetly looks like memory leak - tens of thousands instanses by a few days. I've added logging to `@PreDestroy` method and it haven't called until application undeployed or server stopped. – Anton Batylin Oct 08 '15 at 09:38
  • Yes, seems to be a leak, but are you sure, the reason is in your slsb? May be sfsb is used simewhere else? – Stanislav Oct 08 '15 at 10:01
  • It is used in singletones also, but I have tried to remove it there and result is the same. – Anton Batylin Oct 08 '15 at 11:39