Matthew Hoggan
Matthew Hoggan

Reputation: 7604

Java and Memory Leaks

I am returning to Java after a 5 year break from it. If I remember correctly the Garbage collector would kick in and collect the 'new' memory after subsequent calls to setListAdapterStrings(String [] data)? To be more general does anyone have a preferred set of documentation they like to use when it comes to producing memory leaks while using the JVM?

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;

public class MainActivity extends ListActivity {
    private ListAdapter mListAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);

        createAdapter();
        setListAdapter(mListAdapter);
    }

    protected void createAdapter() {
        // Create some mock data
        String[] testValues = new String[] {
                "Hello",
                "Welcome",
                "The",
                "Java",
                "Test",
                "World",
        }; 
        setListAdapterStrings(testValues);
    }

    public void setListAdapterStrings(String [] data) {
        mListAdapter = new ArrayAdapter<String>(
                this, 
                android.R.layout.simple_list_item_1, 
                data);
    }
}

Upvotes: 1

Views: 301

Answers (1)

Thorn G
Thorn G

Reputation: 12776

No, that is not a memory leak. Java does not require explicit free-ing of memory. The now-unreferenceable ListAdapters will be collected in the future by the Garbage Collector.

Typically, memory is leaked in Java two ways:

  1. Unintentionally retaining references too long
  2. Not properly disposing of lower-level resources (database connections, sockets, etc).

In the first case, "leak" is really a misnomer. It's still reachable, which is why it's not collected, so it can't be said to have leaked, but it's probably not used any more.

Upvotes: 3

Related Questions