Java programmer--Beware of memory leaks in your code

Source: Internet
Author: User

When you move from c&c++ to a language with garbage collection, the programmer's work becomes easier because you run out of objects and they are automatically recycled, but do Java programmers really need to think about memory leaks? actually otherwise

1. For example-see if you can find a memory leak
Import Java.util.Arrays;PublicClass Stack {Private object[] elements;Privateint size =0;PrivateStaticFinalint default_initial_capacity =16;Public Stack() {elements =New Object[default_initial_capacity]; }Public void Push(Object e) {Ensurecapacity (); elements[size++] = e; }PublicObjectPop() { if (size = = 0) throw new emptystackexception (); return elements[--size];} private span class= "DT" >void ensurecapacity  () {if (Elements.copyof (elements, 2 * size + 1);}       
1.1 Cause Analysis

There is no obvious error in the above program, but this program has a memory leak, with the increase in GC activity, or the increasing memory consumption, the performance of the program will be reduced to show that serious can lead to memory leaks, but this failure situation is relatively small.
The main problem with the code is in the POP function, which is shown below
Let's say that this stack has been growing and growing as shown

When a large number of pop operations are performed, the GC is not freed because the reference is not empty, as shown in

As seen from the view, if the stack is growing first, shrinking, then the objects popped out of the stack will not be garbage collected, even if the program no longer uses these teams in the stack, they will not be recycled, because the stack still holds the reference to this object, commonly known as expired references, this memory leak is very covert.

1.2 Workaround
public Object pop() { if (size == 0) throw new EmptyStackException(); Object result = elements[--size]; elements[size] = null; return result;}

Once the references expire, the references are emptied, and the references are empty.

2. Cache leaks

Another common source of memory leaks is caching, and once you put an object reference into the cache, it's easy to forget, and for that matter, you can use Weakhashmap to represent the cache, which is characterized by the addition of a reference to the key itself, This key has no other references so this map will automatically discard this value

2.1 Code Examples
/*** Created by Liuroy on 2017/2/25.*/Import Java.util.HashMap;Import Java.util.Map;Import Java.util.WeakHashMap;Import Java.util.concurrent.TimeUnit;PublicClass Test {static Map WMap =New Weakhashmap ();Static map map =New HashMap ();Public Static void Init() {String ref1=New String ("Obejct1"); String Ref2 =New String ("Obejct2"); String REF3 =New String ("Obejct3"); String REF4 =New String ("Obejct4"); Wmap.Put (REF1,"ChaheObject1"); Wmap.Put (Ref2,"ChaheObject2"); Map.Put (REF3,"ChaheObject3"); Map.Put (REF4,"ChaheObject4"); System.Out.println"String reference Ref1,ref2,ref3,ref4 disappears"); }Public Static void Testweakhashmap() {System.Out.println"Weakhashmap GC before");for (Object O:wmap.EntrySet ()) {System.Out.println (o); }try {System.GC (); Timeunit.SECONDS.Sleep20); }catch (Interruptedexception e) {TODO auto-generated catch block E.Printstacktrace (); } System.Out.println"After Weakhashmap GC");for (Object O:wmap.EntrySet ()) {System.Out.println (o); } }Public Static void Testhashmap() {System.Out.println"HashMap GC before");for (Object O:map.EntrySet ()) {System.Out.println (o); }try {System.GC (); Timeunit.SECONDS.Sleep20); }catch (Interruptedexception e) {TODO auto-generated catch block E.Printstacktrace (); } System.Out.println"After HashMap GC");for (Object O:map.EntrySet ()) {System.Out.println (o); } }Public Static void Main(string[] args) {Init ();Testweakhashmap ();Testhashmap (); }}/** ResultsString reference REF1,REF2,REF3,REF4 disappearsBefore Weakhashmap GCObejct2=chaheobject2Obejct1=chaheobject1weakhashmap GC after hashmap GC before obejct4 =chaheobject4obejct3=chaheobject3disconnected from the target VM, address: ' 127.0.0.1:51628 ', Transport: ' Socket '  HashMap GC after obejct4=chaheobject4obejct3=chaheobject3 **/       


The above code and diagram shows how weakhashmap automatically releases the cached object, and when the Init function completes, the local variable string reference weakd1,weakd2,d1,d2 disappears, and only a reference to the string object is saved in the static map, you can see that After the GC is called, the HashMap is not recycled, and the cache inside the Weakhashmap is recycled.

Listeners and callbacks

Memory leaks The third common source is the listener and other callbacks, which accumulate if the client registers a callback in the API that you implement, but does not show a cancellation. The best way to ensure that callbacks are immediately treated as garbage collection is to save only his references, such as saving them as keys in Weakhashmap.

Java programmer--Beware of memory leaks in your code

Related Article

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.