Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CDI and pooling

Tags:

java

cdi

pool

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?

like image 765
Petr Mensik Avatar asked May 15 '26 20:05

Petr Mensik


1 Answers

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.

like image 115
JB Nizet Avatar answered May 17 '26 10:05

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!