tip
tip

Reputation: 85

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.

Upvotes: 3

Views: 3239

Answers (3)

Alcanzar
Alcanzar

Reputation: 17165

The other answers don't take into account that you are talking about a Thread Pool. Here's what you'd need to do:

private static class MyThreadFactory implements ThreadFactory {
    public Thread newThread(final Runnable r) {
        return new Thread() {
            public void run() {
                try {
                    r.run();
                } finally {
                    // teardown code
                }
            }
        };
    }

}
public static void main(String[] args) {
    ThreadPoolExecutor exec = new ThreadPoolExecutor(10, 20, 100, TimeUnit.SECONDS, null, new MyThreadFactory());
}

Upvotes: 3

Solomon Slow
Solomon Slow

Reputation: 27190

Taking dasblinkenlight's answer a little further (too far?):

class ThreadWithCleanup extends Thread {
    final Runnable main;
    final Runnable cleanup;

    ThreadWithCleanup(Runnable main, Runnable cleanup) {
        this.main = main;
        this.cleanup = cleanup;
    }

    @Override
    public void run() {
        try {
            main.run();
        } finally {
            cleanup.run();
        }
    }
}

public class Demo {
    public static void main(String[] args) {
        Runnable m = new Runnable() {
            @Override
            public void run() {
                System.out.println("Hello from main.");
                throw new RuntimeException("Bleah!");
            }
        };
        Runnable c = new Runnable() {
            @Override
            public void run() {
                System.out.println("Hello from cleanup.");
            }
        };
        ThreadWithCleanup threadWithCleanup = new ThreadWithCleanup(m, c);
        threadWithCleanup.start();
        try {
            threadWithCleanup.join();
        } catch (InterruptedException ex) {
        }
    }
}

And I used to think I would never see a legitimate reason to extend the Thread class!

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726929

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.

Upvotes: 3

Related Questions