Search code examples
javamultithreadingdisposeteardown

How can I execute code when exiting a thread


I want to execute code at the very end before a thread dies. So what I am looking for is some kind of dispose(), tearDown() method for threads guaranteeing that certain tasks are performed before exiting the thread.


Solution

  • You can wrap the code to be executed in a separate thread in your own code that has a try/ finally block, and call the run method of the "real" Runnable from the try, like this:

    final Runnable realRunnable = ... // This is the actual logic of your thread
    (new Thread(new Runnable() {
        public void run() {
            try {
                realRunnable.run();
            } finally {
                runCleanupCode();
            }
        }
    })).start();
    

    The code of runCleanupCode() will be executed in the same thread that was used to run the logic of your actual thread.