What is an elegant way for calling a custom close-method on each worker-thread in a Java threadpool?
say I'm using a
ExecutorService开发者_开发百科 ex = Executors.newFixedThreadPool(nrofthreads);
spinning up some work and waiting when it's done.
However I have same Threadlocal objects in the worker-threads which need to be closed when the batch is done. Therefore, I would like to be able to call a custom close-method on all worker-threads created by the threadpool.
What would be the most elegant way to do that?
Right now as a hack I'm using:
for(int i =0 ; i<20; i++){ //make sure to touch all threads with 20 runs..
ex.execute(new Runnable(){
public void run(){
tearDownThreadLocals();
}
});
}
ex.shutdown();
but that doesn't look particulary robust to me ;-)
Thanks GJ
You can use Executors.newFixedThreadPool(int, ThreadFactory)
to pass a ThreadFactory
, something like this:
ExecutorService ex = Executors.newFixedThreadPool(nrofthreads,
new ThreadFactory() {
public Thread newThread(final Runnable r) {
return new Thread(new Runnable() {
public void run() {
try {
r.run();
} finally {
tearDownThreadLocals();
}
}
});
}
});
EDIT: Just noticed that Executors
already has a method that accepts a ThreadFactory
, so no need to create ThreadPoolExecutor
explicitly.
精彩评论