0

In existing (presumably) working code I see the following construct:

void someFunc() {

    some_irrelevant_code();

    new Runnable() {
        Handler handler = new Handler();
        @Override
        public void run() 
        {
            //will run each 5 seconds
            doSomething();

            if (!needStopSomeThread)
            {
                handler.postDelayed(this, 5000);
            }
        }
    }.run();
}

I wonder if the Runnable and the Handler may be garbage-collected at an arbitrary moment. It looks like only the runnable references the handler, and only the handler references the runnable, so they may be both garbage-collected, unless Android has a data structure referencing one of them, e.g. the handler.

1) Can they both (the handler and the runnable) get garbage-collected?

2) If they can get garbage-collected, how can I prove it actually happens?

18446744073709551615
  • 16,368
  • 4
  • 94
  • 127
  • 1
    I believe the answer to your question is here: http://stackoverflow.com/a/14601968/1127492 – Stefan Jan 21 '15 at 12:23
  • @Stefan: so, can they be both garbage-collected? (I do not see how it may follow from that link.) – 18446744073709551615 Jan 21 '15 at 12:45
  • See the code of the LooperThread (in the answer mentioned above), how to use the handler in a Thread. If the looper thread is terminated an can be gc'ed so can the handler. – Stefan Jan 29 '15 at 10:52
  • @Stefan you mean that if the looper thread is not explicitly terminated (and it does not terminate implicitly), it will reference the handler, and, consequently, the runnable. Right? – 18446744073709551615 Jan 29 '15 at 11:55
  • Yes. The thread usually is implicitly terminated when the activity or the service terminates. – Stefan Feb 10 '15 at 16:35

0 Answers0