Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by sciSpider Java v3.0

...

Code Block
bgColor#FFCCCC
public class Leak {
  static Vector vector = new Vector();
  public void leakingVector(int count) { 	
    for (int n = 0; n <&lt; count; n++) {
      vector.add(Integer.toString(n));
    }
    for (int n = count - 1; n >&gt; 0; n--) { // Free the memory
      vector.removeElementAt(n);
    }	
  }

  public static void main(String[] args) throws IOException {
    Leak le = new Leak();
    int i = 1;
    while(true) {
      System.out.println("&quot;Iteration: "&quot; + i);
      le.leakingVector(1);
      i++;
    }
  }
}

...

Code Block
bgColor#ccccff
for (int n = count - 1; n >&gt;= 0; n--) {
  vector.removeElementAt(n);
}	

...

Code Block
bgColor#FFCCCC
public class BadScope {
  private HashMap<Integer,String>HashMap&lt;Integer,String&gt; hm = new HashMap<Integer,String>HashMap&lt;Integer,String&gt;();
  
  private void doSomething() {
    hm.put(1,"java"&quot;java&quot;);  // hm is used only here
  }
}

...

Code Block
bgColor#ccccff
public class GoodScope {
  private void doSomething() {
    HashMap<Integer,String>HashMap&lt;Integer,String&gt; hm = new HashMap<Integer,String>HashMap&lt;Integer,String&gt;();
    hm.put(1,"java"&quot;java&quot;);
  }
}

Noncompliant Code Example

...

Code Block
bgColor#FFCCCC
public class LapseEvent extends JApplet   {
  JButton button;
  public void init() {
    button = new JButton("&quot;Click Me"&quot;);
    getContentPane().add(button, BorderLayout.CENTER);
    Reader reader = new Reader();
    button.addActionListener(reader);
    try {
      reader.readSomething();
    } catch (IOException e) { 
      // Handle exception 
    }		 
  }
}

class Reader implements ActionListener{
  public void actionPerformed(ActionEvent e)  {
    Toolkit.getDefaultToolkit().beep();
  }
  public void readSomething() throws IOException {
    // Read from file
  }
}

...

Code Block
bgColor#FFCCCC
class HashMemLeak {
  private Map<SSLSocketMap&lt;SSLSocket, InetAddress>InetAddress&gt; m = Collections.synchronizedMap(new HashMap<SSLSocketHashMap&lt;SSLSocket, InetAddress>InetAddress&gt;());
  public void storeTempConnection(SSLSocket sock, InetAddress ip) {
	m.put(sock, ip);  
  }
  public void removeTempConnection(SSLSocket sock) {
	m.remove(sock);  
  }	
}

...

Wiki Markup
This compliant solution uses _weak references_ to ameliorate the issue. Strong references typically used in code, do not allow the garbage collector to reclaim the objects that are stored compositely, such as in a {{Map}}. According to the Java API \[[API 06|AA. Java References#API 06]\], weak reference objects: "&quot;... do not prevent their referents from being made finalizable, finalized, and then reclaimed"&quot;.

A referent is the object that is being referred to. As soon as any strong references to the object are found to have phased out, the garbage collector reclaims the referent. With WeakHashMap, the map's key is weakly referred to and as a result determines whether the corresponding referents are ready to be collected.

Code Block
bgColor#ccccff
// ...
private Map<SSLSocketMap&lt;SSLSocket, InetAddress>InetAddress&gt; m = Collections.synchronizedMap(new WeakHashMap<SSLSocketWeakHashMap&lt;SSLSocket, InetAddress>InetAddress&gt;());
// ...

Wiki Markup
It is not enough to facilitate the collection of unneeded objects with weak references. It is critical to prune the data structure so that more entries can be accommodated in the newly created space. This can be achieved by calling the {{get()}} method of {{WeakHashMap}} and removing the entry that corresponds to the {{null}} return value (polling). A more efficient method is to use a reference queue. \[[Goetz 05b|AA. Java References#Goetz 05b]\]

...

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

Wiki Markup
\[[API 06|AA. Java References#API 06]\] Class Vector, Class WeakReference
\[[Gupta 05|AA. Java References#Gupts 05]\]
\[[Bloch 08|AA. Java References#Bloch 08]\] Item 6: Eliminate obsolete object references
\[[Commes 07|AA. Java References#Commes 07]\] Memory Leak Avoidance
\[[Goetz 05|AA. Java References#Goetz 05]\] Lapsed listeners
\[[Goetz 05b|AA. Java References#Goetz 05b]\] "&quot;Memory leaks with global Maps"&quot; and "&quot;Reference queues"&quot; 
\[[MITRE 09|AA. Java References#MITRE 09]\] [CWE ID 401|http://cwe.mitre.org/data/definitions/401.html] "&quot;Failure to Release Memory Before Removing Last Reference (aka 'Memory Leak')"&quot;

...

MSC00-J. Eliminate class initialization cycles      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;49. Miscellaneous (MSC)      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;MSC02-J. Avoid cyclic dependencies between packages