views:

65

answers:

1

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

+3  A: 

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.

axtavt
Would you want to put: try { r.run(); } finally { tearDownThreadLocals(); } to ensure its always called regardless of how run works out?
Mike
@Mike: Yes, good spot.
axtavt