October 09, 2001, 12:00 AM — You may understand the concepts of activation and passivation -- the
acts of turning a bean "on" and "off", respectively. What the terms,
and to a lesser extent the associated methods in the
javax.ejb.SessionBean and javax.ejb.EntityBean interfaces (ejbActivate
() and ejbPassivate()), actually mean depends on whether they're
applied to a stateless session bean, an entity bean, or a stateful
Entity beans and stateless beans, under most application servers, never
really die. Instead, instances of such beans are "pooled" and made to
wait for another request that requires their services. When they're
pooled, entity beans are not associated with any EJBObject (which can
usually be read as "unique record in a database").
Instances of stateful beans, on the other hand, are usually destroyed --
removed from the volatile memory controlled by the container that's
running the beans -- but not eliminated completely. Their serializable
properties -- those fields that are specific to the state of the
session bean -- are written to disk by the container. Because the
serializable portions of the object are stored persistently, a new
stateful bean can be created and populated with the appropriate session-
specific information when the session comes back to life.
In most cases, the issue of when passivation happens is up to the
container and usually depends on how much demand there is for the
memory the bean instances are tying up. The container can choose to
passivate a bean when it sees that the use of that bean has slowed, and
it figures -- by whatever optimization algorithm it employs -- that it
would be better off passivating and possibly re-activating the bean
than leaving it active but unused.
If the bean server manages activation and passivation, then what are
ejbActivate() and ejbPassivate() for? They can almost be thought of as
event handlers. The first method tells the bean that it's just been
activated; the second tells the bean it's about to be passivated. The
bean's code can react to calls to these methods however it likes.