This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
What you've described is more or less the only way to destroy the Resource object "immediately" when it is no longer needed.
If the clients won't tell you when they're done using the resource, your only other option I know of is to use weak references inside the factory to hold on to the Resource object it is handing out to clients. When client-1 requests the Resource, the factory creates the Resource object, stores it into an internal Map using a java.lang.ref.WeakReference, and returns the Resource object to client-1. Then, client-2 comes and requests for the same Resource so the factory picks up the WeakReference from the Map, asks for the object from the WeakReference, and return the object to the client. And so forth. What the WeakReference accomplished for you is that the Resource object is available for garbage collection as soon as any clients have released their references to it -- the factory's weak reference doesn't prevent the Resource object from being GC'd.
Obviously the garbage collection isn't immediate so this might not be a viable solution to your problem.
Fortunately clients will inform the factory when they are done using the Resource.
In case they are not able to do it due to some reason, the WeakRefernece solution does not make it possible to call destroy method, right?
I am asking this because, the init method of the Resource creates a Timer and schedules a thread to run every 10 minutes. The destroy() does a timer.cancel(). If the Resource object is GC'd by using WR solution does the timer get canceled as well.(TimerTask implemenation class is an inner class of Resource) I am not sure it will gets canceled. It may run forever. Please let me know If I am wrong here.
Thanks again for your help.
Joined: Jan 23, 2002
Originally posted by Pradeep Bhat: In case they are not able to do it due to some reason, the WeakRefernece solution does not make it possible to call destroy method, right?
You could make Resource implement finalize() and invoke the destroy() method from there. The only problem should be that you really have no idea whether the finalize() method is called 5 seconds or 5 minutes after all the references to the Resource object have been released.