Complaints about bean removal

image with no caption

Implementing ejbRemove()

ejbRemove()

Release any resources, or do whatever clean-up you need to do before the bean dies forever. Much of the time, your ejbRemove() method will be empty, because if your bean does use resources, it most likely will acquire and release the resources in each business method. But if your design does call for keeping resources open throughout the bean’s life, then you need to free them up here!

image with no caption

an alternative...

Call a cleanUp() method from both ejbPassivate() and ejbRemove(). Given that your bean could be removed without an ejbRemove() call, if it times out while passivated, you should have both your ejbPassivate() and ejbRemove() methods perform the same clean-up. Since scarce system resources are seldom Serializable anyway, you’re probably already taking care of them in ejbPassivate().

public void ejbRemove() {
   this.cleanUp();
}

public void ejbPassivate() {
   this.cleanUp();
}

private void cleanUp() {
  try {
     myResource.close();
  } catch(Exception ex) {...}
}

Note

now both ejbRemove() and ejbPassivate() will do the same thing, so even if you time out while passivated, you don’t have to worry.

Missed ejbRemove() calls

image with no caption
image with no caption

Watch it!

You must be able to recognize scenarios in which ejbRemove() will be missed!

The exam expects you to know that there are three circumstances under which a bean will NOT get an ejbRemove() call:

  1. Server crashes.

  2. Bean times out while passivated.

  3. Bean throws a system exception.

If any of these happen, your clean-up code will not run. If you follow the suggestions on the previous page, and put clean-up code in both ejbPassivate() and ejbRemove(), then you’re probably OK for problem #2 (timeout while passivated), but you’ll still have to deal with a server crash or bean system exception.

And don’t expect a simple, obvious question like, “Will a bean miss an ejbRemove() if a system exception is thrown?” You might have to consider a design scenario, for example, and figure out if there could be a problem, based on your knowledge of missed ejbRemove() method calls.

Get Head First EJB now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.