I have seen the @PrePassivate
and @PostActivate
annotations in every EJB tutorial, but I don't see how are they useful. What would be an scenario where I need those?
Most of the times when you are using Stateful Session Beans (which is not recommended really, except for some rarely needed conditions) this can be useful for the container to manage and re-use some inactive connections at some point of time, to help keep the number of connection taken from your database at some optimum count.
For example your DBMS can manage 1000 connection. So you may create a connection pool of size 1000 in your container (Application Server e.g. GlassFish, Weblogic, ...).
Then when your application reaches to the number of 1000 session for example, if another user wants to be enter to your application, he/she should wait until one of the 1000 connections is released.
In this situation, a mechanism of Passivate/Activate
may be useful. As it's obvious Passivate/Activate
is not happening in small application. But for some highly used applications with huge number of concurrent users this may happen due to the pool size, inactive time-out, and some other parameters.
Example scenario:
Maybe at least 200 out of 1000 connections are taken for some data entry in some big forms with a lot of fields. So the user may at least take 2 or 3 minutes to complete the data entry. In this 3 minute the connection which is dedicated to a stateful session bean is inactive and can be used for other users (Other session beans).
So after a specified time out the container would passivate
the current state of the session bean (serialize them to a specific database or file or memory) and release its connection to the connection pool to be used.
When the the user completed the form and clicked on submit button, the container would re-allocate the connection from the pool if available and activate
the previously passivated state of that session bean to continue the business from the exact state prior to the passivation.
So @PrePassivate
and @PostActivate
are useful for you if you need to do some manual operation at that events.
Hope this would be helpful.