Search code examples
javacdipool

CDI and pooling


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?


Solution

  • 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.