#
@PrePassivate vs @PostActivate
This tutorial will explain to you the role of the @PrePassivate & @PostActivate annotation in EJB.
Because a conversation with a client may be long-lived and sometimes the client could be inactive for a long time, the EJB container have a mechanism of releasing resources that may not be needed at some precise moment. This is where EJB passivation and activation comes into: The container may passivate an EJB that is not needed at some point in time and later activate it as soon as it's needed again.
Using the annotation we can tell the EJB container to do something "Before Passivating" (@PrePassivate) and "After Activating" (@PostActivate) the Stateful EJB.
This mechanism in Java is used only for the Stateful EJB.
Here is an example of EJB using the @PrePassivate and @PostActivate annotation in Java:
import java.awt.Toolkit;
import java.util.Date;
import javax.ejb.PostActivate;
import javax.ejb.PrePassivate;
import javax.ejb.Stateful;
@Stateful(mappedName="/AddIntegers")
public class AddIntegers implements AddIntegersRemoteInterface {
private int sum_var;
private Date date = new Date();
public AddIntegers() {
super();
sum_var = 0;
}
@Override
public void addValue(int a) {
// What the EJB3 will return
sum_var = sum_var + a;
}
@Override
public int returnSum() {
// What the EJB3 will return
return sum_var;
}
@PrePassivate
private void prePassivate(){
// Do something ...
}
@PostActivate
private void postActivate(){
// Do something ...
}
}
Info
For all the EJB we can use the @PostConstruct and @PreDestroy annotation as well.