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 aThreadFactory, something like this:EDIT: Just noticed that
Executorsalready has a method that accepts aThreadFactory, so no need to createThreadPoolExecutorexplicitly.