3

Does CDI allows pooling in some way?Because I thought this is a feature of EJB beans but Adam Bien says in this screencast that container chooses whether to create new instance of class through reflection or use the existing one. So if I have for example these two beans

@RequestScoped
public class RequestBean {

    public void doIt() {

    }
}

@SessionScoped
public class SessionBean {

    @Inject
    private RequestBean bean;    

    public void doSomething() {
        bean.doIt();
    }
}

the question is - is there always new instance of RequestBean created upon calling doSomething or does CDI container somehow manage instances in pool?

Petr Mensik
  • 26,874
  • 17
  • 90
  • 115

1 Answers1

10

The first one is scoped to the request, so a new instance is created for each request. The second one is scoped to the session, so a new one is created for each session.

CDI doesn't pool and recycle the objects, because it has no idea if the objects are stateful or not, and you don't want, in a request, to get back the state that a bean had in a previous request. That would ruin the whole point of the request/session scope.

Unless beans are really costly to create (because they start a new connection or something like that), pooling them doesn't bring any advantage. Short-lived objects are very fast to create and garbage collect nowadays. And if the bean is really expensive to create, then it should probably be a singleton.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • 1
    But maybe one question - based on what have said, what's the point of Stateless beans pooling in EJB, isn't it the same?I suppose what container does is creating a stateless bean, putting it into pool, then withdraw it upon request and then reset all fields to null and put it back to pool. So why does this work with `Stateless` beans and not with `RequestScoped` ones, I am not sure if I can see the difference. (EJB Stateless bean and CDI RequestScoped seems to me pretty similar) – Petr Mensik May 23 '13 at 21:10
  • 1
    A Stateless bean is supposed to be stateless. So it shouldn't have conversational state, and the developer knows that if he stores something in a field, he could get it back when reused later. If stateless beans were invented now, they would probably not be pooled. But they were invented at a time (around the year 2000) when object allocation was not as fast as it is now, and when we didn't have all the experience we have now. – JB Nizet May 23 '13 at 21:33
  • So they invented EJBs because they didn't realise that CDIs were so simple to instantiate as today ? Pretty simple solution. – fidudidu Aug 02 '19 at 08:17
  • And you say that Garbage Collecting is faster cleaning objects in memory than to allocate and reuse them? Brilliant. – fidudidu Aug 02 '19 at 08:19