[concurrency-interest] "Best practice" for ThreadPool creation/run-down

Gregg Wonderly gregg at cytetech.com
Tue Jan 8 17:02:03 EST 2008

Aaron wrote:
> Peter,
>    I had a chat with a co-worker about this. If exposing a lifecycle 
> interface isn't an option (probably the best route in cases where a 
> thread pool is created), a PhantomReference may do what you want. When 
> no other references to your pool-holding object exist, you can shutdown 
> your thread pool.
> http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ref/PhantomReference.html

I posted a class that provides use of PhantomReference mechanism to track 
things.  I can send it to anyone directly that wants it.  The usage is to create 
a subclass that accepts the object to track and the object to cleanup.

class MyTracker extends ReferenceTracker<RefObjectType,CleanupObjectType> {
	public void release( CleanupObjectType obj ) {
		... do something with obj to cleanup ...

The cleanup object can not have a strong reference to the tracked object.  Then, 
you can use the instance as in
class MyClassThatCreatesObjectsThatNeedCleanup {
	private static final MyTracker tracker = new MyTracker();

	public RefObjectType creatorMethod() {
		CleanupObjectType refToThingToCleanup = ...initialize...;
		// refToThingToCleanup is typically referenced by
		// RefObjectType instances
		RefObjectType obj = ...create object...( ... );
		tracker.trackReference( obj, refToThingToCleanup );
		return obj;

In Peter's case, I am not sure what "thing" is the always referenced object 
whose loss of reference would trigger the cleanup.  The Threads in the 
ThreadPool stay referenced even if they are not running anything.  So, it seems 
that another thing would need to be referenced and then when that reference 
dies, the thread pool would be shutdown.

Gregg Wonderly

More information about the Concurrency-interest mailing list