1. What is a memory leak
When some objects are no longer used by the application, but are still referenced, the garbage collector cannot be freed (remove)
2. Causes of memory leaks
Long-life-cycle objects that hold references to short-life-cycle objects are likely to have a memory leak (old-age reference generation)
2.1 When the object property inside the collection is modified, it does not work because hashcode changes when the Remove () method is called again
1 ImportJava.util.HashSet;2 ImportJava.util.Set;3 4 /**5 * Created by Xiaoxiao7 on 2016/11/9.6 */7 Public classTest01 {8 9 Public Static voidMain (string[] args) {TenSet<string> set =NewHashset<string>(); OneString str1 =NewString ("AAA"); AString str2 =NewString ("BBB"); -String STR3 =NewString ("CCC"); - Set.add (str1); the Set.add (str2); - Set.add (STR3); -System.out.println ("Before:" +set.size ()); -STR3 = "DDD"; + Set.remove (STR3); - Set.add (STR3); +System.out.println ("After:" +set.size ()); A for(String str:set) { at System.out.println (str); - } - } -}
2.2 Static collection classes cause memory leaks
1 ImportJava.util.HashSet;2 ImportJava.util.Set;3 ImportJava.util.Vector;4 5 /**6 * Created by Xiaoxiao7 on 2016/11/9.7 */8 Public classTest01 {9 Ten StaticVector v =NewVector (10); One A Public Static voidMain (string[] args) { - for(inti = 1; i<100; i++) - { theObject o =NewObject (); - V.add (o); -o =NULL; - } + } -}
Java memory leaks