java - Will this particular use of an anonymous Runnable cause a memory leak? -


private class productfragment extends fragment implements ongetproductfromdblistener {      activity a;      void oncreate {          = getactivity();         new getproductfromdb();     }       void ongetproductsuccess(product product) { // not called main thread because of implementation of getproductfromdb         a.runonuithread(new runnable() {              void run() {                 // ui , views related stuff             }          });     }   } 

now, runnable being anonymous class should hold explicit reference fragment, right? , prevent fragment being garbage collected?

should worry memory leak occurring , how should prevent it?

will if instantiate class extends runnable , make static?

private static class runnabletask extends runnable {     productfragment fragment;     public runnabletask (productfragment fragment) {        this.fragment = fragment;     }      void run() {         if(fragment.someboolean) {            fragment.dosomething();        }      } }  runnabletask runnable = new runnabletask(); a.runonuithread(runnable) 

strictly speaking, won't result in memory leak. - duration of thread's run hold reference outer class (productfragment in case). whether it's memory leak depend on how long thread run for, , whether ends being reference left productfragment class.

your suggestion of breaking out static inner class 1 remove reference outer class , hence remove chance of potential memory leak.

however - in case, seeing proposed static class holds on reference of outer class instance anyway, there no benefit doing this.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -