0

I've written a Utilloader class which provide a loader thread that load some data from net. in my activity I start a new loader thread. The thread then update the activity via handler.post().

class MyActivity extends Activity
{
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    initUI();
    UtilLoader.getInstance().load("url", new UtilLoad.OnLoadListener
    {
      public void onLoadSuccess(String response)
      {
         updateUI();
      }
    });
  }
}

class UtilLoader
{
  private Handler handler = new Handler();
  private UtilLoader instance = new UtilLoader();
  private ExecutorService executorService = Executors.newFixedThreadPool(3);
  public interface OnLoadListener
  {
    public void onLoadSuccess(String response);
  }
  public UtilLoader getInstance()
  {
    return instance;
  }
  public load(String url, OnLoadListener onLoadListener)
  {
    executorService.submit(new Loader(url, onLoadListener));
  }
  public class Loader extends Runnable
  {
     private String url;
     private OnLoadListener onLoadListener;
     public Loader(String url, OnLoadListener onLoadListener)
     {
        this.url = url;
        this.onLoadListener = onLoadListener;
     }
     public void run()
     {
        // LOAD DATA
        handler.post(new Runnable() {        
           public void run() {
             onLoadListener.onLoadSuccess(sb.toString());
           }
        });
     }
  }
}

Does this way of activity updating result in memory leaks by keeping a reference to the activity? If yes how must I change it, so there is no memory leaks?

Ali
  • 21,572
  • 15
  • 83
  • 95
  • yes, if you are setting a callback i.e. updateUI() it will definitely result in memory leak by keep a reference to it thus preventing the GC from collecting it. – Jitender Dev Nov 07 '13 at 09:06

3 Answers3

0

Yes, the UtilLoader holds a reference to the anonymous inner class which you pass in as OnLoadListener and this anonymous inner class in turn holds a reference to the activity.

Henry
  • 42,982
  • 7
  • 68
  • 84
0

yes, if you are setting a callback i.e. updateUI() it will definitely result in memory leak by keep a reference to it thus preventing the GC from collecting it.

Jitender Dev
  • 6,907
  • 2
  • 24
  • 35
0

It's possible. As long as the Looper associated with the handler has messages in the queue, it will keep a reference to the associated Activity/Service. This could be a problem for long-running operations. See this thread for more:

This Handler class should be static or leaks might occur: IncomingHandler

Community
  • 1
  • 1
Anup Cowkur
  • 20,443
  • 6
  • 51
  • 84