Java memory leaks

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.