If you want to look clever just talk about Threads!

Yeah, that’s true. If you want to look clever, just talk about Threads. Talk about threads everywhere, on job interview or in company you’re working for or with your fellow programmers. Don’t talk about Threads with your girlfriend / boyfriend. She / He maybe know what you are talking about.

If you start talking about threads and everybody look at you confused, than you are doing good. But if somebody understands what you are talking about, than maybe you have a problem.

Threads are something scary. Nobody saw them before!

Well you can close your eyes and pretend that Threads don’t exist, but they do. They are there and they are nice tool to help you doing very interesting stuff in Android.

What? How? Interesting?

Don’t block UI or Main Thread.

If you think that row above is empty because of some glitch or error, that’s a mistake. The row above is not empty. If you try to select it, you will see one of the most important and crucial thing in Android:

Don’t block UI or Main Thread.

So, now you know. There is Main thread in Android. Main thread or UI thread is one of the most important concepts in Android, usually used to draw everything on the screen. So, you see now. There is one thread in Android. Main thread. Now you know.

But what does that mean?

After each configuration change, the Android system creates a new Activity and leaves the old one behind to be garbage collected. However, if the thread holds an implicit reference to the old Activity and prevents it from ever being reclaimed. As a result, each new Activity is leaked and all resources associated with them are never able to be reclaimed.

The fix is easy: declare the thread as a private static inner class as shown below.

public class MyThreadActivity extends AppCompatActivity {

    private MyThread mThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        goFetchData();
    }

    private void goFetchData() {

        mThread = new MyThread();
        mThread.start();
    }

    /**
     * Static inner classes don't hold implicit references to their
     * enclosing class, so the Activity instance won't be leaked across
     * configuration changes.
     */
    private static class MyThread extends Thread {

        private boolean mRunning = false;

        @Override
        public void run() {

            mRunning = true;

            while (mRunning) {
                SystemClock.sleep(1000);
            }
        }

        public void close() {
            mRunning = false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        mThread.close();
    }

}

In progress. More will follow soon…

Leave a Reply