Search code examples
javamemory-leaksstaticclass-variables

Defining a static List could lead to memory leakage?


If I define a static variable in my class as follows:

class MyClass
{
  private static List<String> list = new ArrayList<String>();
}

Can list cause memory leakage? If yes, then how?


Solution

  • The snippet of code you posted is a memory leak in the sense that if you never clear elements from that list or set it to null, it will keep growing and not get garbage collected.

    With non-static lists (instance or local scoped lists), this would happen much less often. With non-static variables, once the instance goes out of scope, so does the variable (and possibly the object), so it can get garbage collected. With static variable, they can never go out of scope (unless you set the reference to null , which you can't do on final) since they're linked to the class.