Rule Definition
In a production environment, memory leaks can force organizations to add more memory and hardware resources. They can even cause an application to crash unexpectedly. In theory, the garbage collector is responsible to manage memory and should avoid these issues.
In practice, static collection classes, such as HashMap and Vector can cause memory leak. Static collections are likely to cause memory leaks because static variables remain in memory as long as the application runs, regardless of its object creation and destruction. So because their life cycle is the application duration, the objects that they reference will be kept in memory until the application end.
Remediation
You can either check that objects added in the collection are removed when required or use weak references that will leverage the garbage collector's ability to determine reachability of referenced objects for you.
Violation Code Sample
class Sample {
// VIOLATION
static HashMap my_map;
...
}
Fixed Code Sample
class Sample {
// FIXED
static WeakHashMap my_map;
...
}
Reference
http://weblogs.java.net/blog/enicholas/archive/2006/05/understanding_w.html
http://websphere.sys-con.com/read/44716.htm
Related Technologies
JEE
Technical Criterion
CWE-401 - Missing Release of Memory after Effective Lifetime
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.