Java ExecutorService callback on thread terminate?

In your ThreadFactory code, create the instance of Thread such that it will try to do the work of the Runnable it is created for and then finally do your cleanup work. Like this.

Up vote 3 down vote favorite share g+ share fb share tw.

I am using cached thread pool ExecutorService to run some asynchronous background tasks. I've provided my ThreadFactory that hands out threads to the ExecutorService (whenever it needs them). My understanding of the cached thread pool is that after the thread is sitting idle for 60 seconds it is termniated by the ExecutorService.

I want to perform some state cleanup when my thread is about to be terminated. What is the best way to achieve this? The ExecutorService does not readily provide hooks into the thread's lifecycle.

I don't want to shutdown my ExecutorService - useful for running tasks as and when they come. ExecutorService executor = Executors. NewCachedThreadPool(new MyThreadFactory()); // Do some work executor.

Submit(new MyCallable()); // Need a way for the ExecutorService to notify me when it is about to // terminate my thread - need to perform some cleanup Thanks, Shreyas java multithreading threadpool executorservice link|improve this question asked May 2 '11 at 21:26Shreyas Shinde182.

1 for interesting question. I wonder if a finalizer would work? – Rom1 May 2 '11 at 21:43 @Rom1, someone had posted in answer suggesting implementing finalize.

I think it is too bad they deleted it. What should be noted is that using finalize means incurring some performance hits in the GC and JVM. – Tim Bender May 2 '11 at 23:04 I tried to use the finalize approach but it didn't work.

The method was not getting called. – Shreyas Shinde May 2 '11 at 23:14 @Tim, sure, the accepted answer looks a lot better than meddling with finalizers – Rom1 May 3 '11 at 7:13.

In your ThreadFactory code, create the instance of Thread such that it will try to do the work of the Runnable it is created for and then finally do your cleanup work. Like this: public Thread newThread(final Runnable r) { Thread t = new Thread() { public void run() { try { r.run(); } finally { //do cleanup code } } }; return t; }.

Just plain awesome! Thanks Tim! – Shreyas Shinde May 2 '11 at 22:04 Another option is to use a fixed size thread pool and never clean up.

Freed memory is never passed back to the OS, so you may be adding complexity without a benefit. – Peter Lawrey May 2 '11 at 22:15.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions