Generally, you put clean-up code to clean up non-memory related resources in the finalize() method so that when the object is about to be garbage collected, those resources are gracefully released. Examples for non-memory related resources include File, Socket, etc.
In case of EJBs, the life-time of a bean instance is controlled by the container. i.e, the container decides when to instantiate, activate, passivate, remove and associate an instance to EJBObject (to client). So you cannot rely on the code that you may put in the finalize() method. In other words, you may want the finalizer to run when a bean is no longer needed by a client .i.e, the client has invoked remove(), but the container may move the instance back to pool, in which case the finalizer will not be run.
OK. How do we discard an instance in
Java?
In plain Java , we assign someObject = null. The object now becomes eligible for GC, finalizer runs and the instance is killed and memory is recovered.
But in
EJB world, assigning null doesn't simply work. The client must invoke the remove() method on the remote object, so that the container can free the instance. But this does not mean that the bean instance associate with the EJBobject will be GCed. The container may move the instance back to pool. So there is no guarantee that finalizer will be run when an EJB instance is discarded (removed) by a client.