I wonder how applying the different bean scopes in CDI (@ApplicationScoped
, @SessionScoped
and @RequestScoped
) works. I understand the life cycle, but where in the container are these stored? I am using these annotations on JSF beans.
How are these beans stored on the server and how is the server capable of knowing which beans belong to who.
For example is a bean that have a @SessionScoped
stored in the HTTPSession
object behind the scenes? Are beans with @ApplicationScoped
stored in a map instance variable in ServletContext
? If so, what about thread safety. I guess I have misunderstood it but it would be great if somebody could teach me what happens, where they are stored (the different scopes), how is the server capable of knowing which beans belongs to who...like are there any other ids (not only session id)?
I am btw using Java EE 6 all Reference Implementations.
Scopes a single bean definition to any number of object instances. Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition.
If you place a managed bean into request scope, a new instance is created with each request. It is worth considering request scope if you are concerned about the cost of session scope storage. ApplicationScope: The application scope persists for the entire duration of the web application.
For example is a bean that has an @SessionScoped stored in the HTTPSession object behind the scenes? Are beans with @ApplicationScoped stored in a map instance variable in the ServletContext?
For the web layer, that is indeed what happens. If the bean has been instantiated you can often find it back there by manually iterating over all objects in said maps.
@RequestScoped
is a special thing though. In the web layer this corresponds with the request attribute map, but this scope also applies to calls to e.g. remote session beans, or message driven beans processing a message. In that case, there is no http request and hence no request attribute map. It's likely that those are stored 'somewhere else', probably in TLS (Thread Local Storage) that's set and unset by the bean proxy.
If so, what about thread safety.
Application- and Session scoped beans are by themselves simply not thread safe. You have to take care of thread-safety, for instance by using thread-safe data structures, the synchronized keyword, or a bean type that's inherently thread-safe (like a @Stateful annotated bean).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With