Xera12
Xera12

Reputation: 221

Android - background thread garbage collection

 public class MainActivity extends appCompatActivity{

        private void taskDone()
        {
            System.out.print("done");
        }

        public void startBackgroundThread()
        {
            new Thread()
            {
                @Override
                public void run()
                {
                 MyLongrunnigTas.perform();
                 taskDone();
                }

            }.start();

        }


        //...

When startBackgroundThread() is called, Will it be garbage collected,after the thread executes, even though the activity is destroyed ( eg. by a orientantion change ).

Or will this cause a memory leak ??

Upvotes: 1

Views: 706

Answers (1)

Gabe Sechan
Gabe Sechan

Reputation: 93569

The thread will be garbage collected according to the normal rules- when no GC roots reference it anymore. Since a running thread is automatically a GC root itself, it won't be possible to collect until after the thread finishes running. Whether its elligble then or not depends on if any other variable holds a reference to it. In your example, where it isn't saved anywhere, it will not be eligible until the thread finishes.

As for the Activity- since the Thread is an annonymous inner class, it will have a reference to the class its defined in- your MainActivity. So until the thread is finished running the MainActivity, and all its variables, will not be garbage collected. This includes the entire View hierarchy, so this is a bad leak.

Upvotes: 2

Related Questions