shanraisshan shanraisshan - 9 months ago 43
Android Question

Passing parameters vs Allocation inside function, memory-leak in java/android?

2 Different ways of doing the same thing (i.e Fetching messages from Database)

  • Scenerio 1

Calling 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

Calling 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, in Scenario 2,

  1. What will happen to temp ArrayList variable,

  2. Will it remain in memory until the activity is destroyed ?

  3. Is it a Memory Leak?


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

Answer Source

The variable itself will go out of scope and be deallocated (as the call stack shrinks).

The object that the variable points to (the ArrayList) still has another reference pointing to it, so it will not be collected.

It will go away when no more references (such as your messages variable or field) exists.

This is not a memory leak.

In both scenarios, it is pointless to create the empty ArrayList before calling the function (and you should be asking yourself what happens to it once you receive the new one, just like you worried about temp. Don't worry, it's only pointless, not dangerous or "leaky").

Do this instead:

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