2

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

Valentin Rocher
  • 11,667
  • 45
  • 59
Geert-Jan
  • 18,623
  • 16
  • 75
  • 137

1 Answers1

4

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
  • 239,438
  • 41
  • 511
  • 482
  • Would you want to put: try { r.run(); } finally { tearDownThreadLocals(); } to ensure its always called regardless of how run works out? – Mike Mar 05 '10 at 11:10