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

Endre Stølsvik Online at stolsvik.com
Tue Jan 8 18:17:11 EST 2008


Peter Kovacs wrote:
> Thank you, Aaron.
> 
> I guess I'll have to read-up on the java.lang.ref package. (I kind of
> suspect that this will not work for me, because the thread pool used
> is ultimately referenced as a static variable in my library. I'll see
> if this is a problem for the PhantomReference scheme.)

Get rid of the static - library-thingies with statics in them are 
annoying, in my opinion. I'd rather like to keep a reference to your 
service-/something/, than to rely on you magically handling things using 
those dreaded memory retaining annoyances which statics are.

And I also like to be able to shut down this /something/ explicitly. I 
positively hate when java databases and message queues and what have 
you, don't let you explicitly shut then fully down. What if I want to 
implement a "reboot" algorithm - cycling the entire application as if 
the JVM terminated, and then fire it up again? (If your memory 
consumption doesn't increase after a bunch of such cycles, and you then 
are able to terminate the application without calling System.exit(x), 
chances are you have every resource under control). This goes doubly for 
the "new-style" stuff using OSGi - here modules are taken up and brought 
down all the time - and I don't like that I cannot explicitly clean up.

Furthermore, I think you should _clearly_, in bold and underline, state 
in the javadocs and docs in general that there IS such a default 
handling using a default thread pool - so that the users know that when 
using your something, a bunch of threads will in any way be created. 
Very good, though, that you provide a way for the user to provide an 
executor themselves - don't then go ahead a stick that into some static!

Finally, you could possibly have a magic clean up procedure that made it 
shut cleanly down if no one was using anymore - as a nod to those people 
that aren't quite that worried about explicit resource handling. But I 
think those reference-ideas won't guarantee that the JVM will be able to 
shut down in a timely fashion without a System.exit(): I don't think the 
JVM instantly enqueues abandoned objects - I believe this is done in the 
same fashion as with garbage collection, and we all know how what 
happens if you rely on finalization for resource shutdown, don't we? :)
   However, you can make a ThreadFactory for your default pool, which 
explicitly sets all those threads to deamon threads. (And please also 
name your threads - that makes it SO much nicer when running the 
application within a JVMTI-hooked IDE (e.g. Eclipse, when using debug 
instead of run, which I though everybody did always), and when actually 
debugging.) Then at least the JVM shutdown aspect would be fixed.

Endre.


More information about the Concurrency-interest mailing list