1

Will this code cause a memory leak if it is present in the Activity VS ViewModel component?

    handlerThread = new HandlerThread("myHandlerThread");
    handlerThread.start();
    Handler handler = new Handler(handlerThread.getLooper());
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            //Do work
        }
    }, 1000);

    @Override
protected void onDestroy() {
    super.onDestroy();
    handlerThread.quit();
}

Will replacing the anonymous runnable class with a static class that extends Runnable make any difference? This was mentioned @4:13 in this video tutorial!

Why would an anonymous runnable hold reference to an Activity or ViewModel?

Mena
  • 3,019
  • 1
  • 25
  • 54

1 Answers1

0

In Java, non-static inner and anonymous classes hold an implicit reference to their outer class. Static inner classes, on the other hand, do not.

Avoid using non-static inner classes in an activity if instances of the inner class could outlive the activity’s lifecycle. Instead, prefer static inner classes and hold a weak reference to the activity inside.

Source 1 Source 2

As for doing the same in the ViewModel instead of an Activity, if a memory leak occurs it will have a lesser magnitude in case the ViewModel didn't hold a reference to memory-intensive objects that should be garbage collected. But still, a memory leak threat would be still possible.

This Link is also very informative

This playlist contains all about how to properly use Handlers/Threads/HandlerThreads

Mena
  • 3,019
  • 1
  • 25
  • 54