Reputation: 1495
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?
Upvotes: 2
Views: 2119
Reputation: 279890
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.
Upvotes: 2
Reputation: 135992
It's not necessarily static Lists (Collection) that may cause a memory leak. If we have a long-living Collection (eg cache) we should limit its size somehow, eg by removing old object form it.
Upvotes: 1
Reputation: 9741
Technically it is a memory leak only if it is out of garbage collector's
reach. On the other hand, if it is in memory for extended periods even when you don't have a use for it, well that's a logical flaw
and it will keep the related objects from getting gc'ed too. The memory will be reclaimed only when the class is unloaded.
Upvotes: 1
Reputation: 2181
Static variables are in classes alloaced in a special memory place meaning, in your app exsists only 1 array Myclass.list
, and the thing is they are not dynamic. So your list has to have a fixed size.
public final static String[] list=new String[]
{"str1", //0
"str2", //1
"str3", //2
"str4", //3
};
You can't modify those values, by result i doubt it will cause leaks.
Upvotes: -1