users@glassfish.java.net

Dependency injection - when to clean up injected resources?

From: Mark Mielke <mark_at_mark.mielke.cc>
Date: Sun, 26 Apr 2009 17:07:14 -0400

This feels like a newbie question - but it seems like this is a friendly
group, and I've read through all of the specs and faqs and plenty of
examples and I have been unable to find a solid answer here.

Most examples of dependency injection do not clean up the injected
resources. Whether DataSource, EntityManager, or EJB. The resource is
injected, it is used, and resources allocated from it (like a Connection
from a DataSource) are cleaned up, but the injected resource itself is
not cleaned up.

My assumption has been that these resources are safe to leave around.
That is, they're only taking up memory which is the job of the garbage
collector to deal with. They're not tying up any resources. In some
cases like EntityManager or a UserTransaction, the container will always
clean up any non-memory references held after the business method
returns when the transaction is committed or rolled back.

This conclusion sat well with me until I started looking into the use of
stateful session beans.

For stateless session beans, my understanding is that the container
manages a pool that is only assigned when a method is invoked, and added
back to the pool when done, so I think stateless session beans are safe
to never explicitly remove.

For stateful session beans, however, nothing in the spec seems to
suggest to me that it will automatically run the @Remove method on a
stateful session bean. But, in many of the examples I find, including
ones on "official" sites like openejb, they eject a new stateful session
bean into the client object and then never remove it. Does this not lead
to the container having stale EJB sessions lying around, perhaps
passivated? If invoked 1 million times, does this leave 1 million
sessions being managed by the container but not being referenced by any
client? Should these examples be corrected?

What is the best place to do this cleanup? Should @PostDestroy method on
the object receiving the injection be explicitly running the @Remove
method on all injected stateful session beans (assuming they are not
being saved for later user)?

What about JSF managed beans that inject using @EJB? Should they also
remove all stateful session beans from the @PostDestroy method?

Are there other dependency injected objects that require explicit
cleanup during @PostDestroy?

Thanks for any help in clearing me up on this.

Cheers,
mark

P.S. I am a happy GlassFish user - hoping Oracle keeps it around.

-- 
Mark Mielke <mark_at_mielke.cc>