Parameter passing vs Distribution within a function, memory leak in java / android?

2 Different ways to do the same (like getting messages from the database)

  • Scenerio 1

Call class:

ArrayList<String> messages = new ArrayList<String>();
messages = Db.getAllMessage(messages);

      

Database class:

public ArrayList<String> getAllMessage(ArrayList<String> m) {
   m= /* get messages from DB */
   return m;
}

      

  • Scenerio 2

Call class:

ArrayList<String> messages = new ArrayList<String>();
messages = Db.getAllMessage();

      

Database class:

public ArrayList<String> getAllMessage() {
   ArrayList<String> temp = new ArrayList<String>();
   temp = /* get messages from DB */
   return temp;
}

      

My question is Scenario 2 ,

  • What happens to the temp ArrayList variable ,
  • Will it stay in memory until the activity is destroyed?
  • Is this a memory leak ?

Edit:

In the Android Application Architecture video (Android Dev Summit 2015) , Adam Powell mentions that GC is your enemy and suggests using scenario 1 in the case of an Android app.

+3


source to share


2 answers


The variable itself will go out of scope and be deallocated (since the call stack is shrinking).

The object pointed to by the variable (ArrayList) still has another reference pointing to it, so it won't be collected.

It will disappear when there are no more references (like your variable or scope messages

).

This is not a memory leak.




In both scenarios, it makes no sense to create an empty ArrayList before calling the function (and you should be asking yourself what happens to it as soon as you get a new one, just as you are worried about temp

it, it's just pointless, not dangerous or "leaky").

Do this instead:

ArrayList<String> messages = Db.getAllMessages();

      

+2


source


The two scenarios are no different.

The list of empty arrays on rhs in scenario 1 is immediately suitable for GC.



A reference to the temp created by the database class in scenario 2 is passed back to the caller. It is local to the database method so that the link is out of scope and its link count is decremented by one.

Also no leak occurs unless the calling class is hanging on a link that took too long to return from the database class.

0


source







All Articles