Rio6
Rio6

Reputation: 198

Should I call thread.join in onDestroy()

Is it good to call Thread.join in onDestroy? Or just tell the thread to stop and leave it?

For example:

public class MyActivity extends Activity {

    private Thread myThread;
    private volatile boolean running = true;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        myThread = new Thread(new Runnable() {
            public void run() {
                while(running) {
                    // Do something
                }
            }
        });
        myThread.start();
    }

    public void onDestroy() {
        super.onDestroy();

        running = false;
        try {
            myThread.join(); // Is it good to calling it here? Or just let it fininsh itself?
        } catch(InterruptedException e){}
    }
}

I know calling join() might block the UI thread, but what would happen if the activity finishes before the thread without calling join()?
What does the system do to the threads after the activity is destroyed? Does it wait for them, put them in background, or kill them?

Upvotes: 1

Views: 498

Answers (1)

Gabe Sechan
Gabe Sechan

Reputation: 93678

No, don't. Thread.join() doesn't destroy a Thread- it waits for it to finish. This could take a very long time (or forever). It should only be called if doing so won't make the app unresponsive (if its not on the UI thread) and if you absolutely cannot continue without that thread being finished. Neither one is true here.

Upvotes: 1

Related Questions