Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Case Analysis of memory leak in Java

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the relevant knowledge of "Java memory leak case Analysis". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Java memory leak problem

The so-called memory leak means that an object or variable that is no longer used by the program has been occupied in memory.

There is a garbage collection mechanism in Java, which ensures that when an object is no longer referenced, that is, when the object becomes an orphan, the object will be automatically cleared from memory by the garbage collector.

Since java has a garbage collection mechanism, why is there a memory leak problem?

It's just that some objects cannot be processed by the garbage collector, causing these objects to occupy JVM memory all the time, which leads to memory leaks.

Because Java uses directed graph for garbage collection management, the problem of reference loop can be eliminated. For example, if there are two objects that reference each other, as long as they and the root process are unreachable, GC can also recycle them. For example, the following code can see the memory recycling in this case.

Import java. Io.IOException;public class GarbageTest {public static void main (String [] args) throws IOException {try {/ / TODO Auto-generated method stub gcTest ();} catch (IOException e) {e.printStackTrace ();} System.out.println ("has exited gcTest!"); System.in.read (); System.in.read () System.out.println ("out begin gc!"); for (int I = 0; I < 100; iTunes +) {System.gc (); System.in.read (); System.in.read ();}} private static void gcTest () throws IOException {System.in.read (); System.in.read (); Person p1 = new Person () System.in.read (); System.in.read (); Person p2 = new Person (); p1.setMate (p2); p2.setMate (p1); System.out.println ("before exit gctest!"); System.in.read (); System.in.read (); System.gc (); System.out.println ("exit gctest!") } private static class Person {byte [] data = new byte [20000000]; Person mate = null; public void setMate (Person other) {mate = other;}

Memory leaks in Java: memory leaks are likely to occur when long-lifecycle objects hold references to short-lifecycle objects. Although short-lifecycle objects are no longer needed, they cannot be recycled because long-lifecycle objects hold its references. This is the scenario of memory leaks in Java. Generally speaking, programmers may create an object. This object has not been used since then, but it has been referenced all the time, that is, the object is useless but cannot be reclaimed by the garbage collector, which is a possible memory leak in java.

For example, in the caching system, we load an object into the cache (for example, in a global map object) and then stop using it. The value of this object is referenced by the cache, but it is no longer used.

Check for memory leaks in Java, be sure to let the program execute all kinds of branches to the end of the program, and then see if an object has been used, and if not, it can be determined that the object belongs to a memory leak.

If the method of an instance object of an external class returns an instance object of an inner class, the inner class object is referenced for a long time, even if the external class instance object is no longer used, but because the inner class persists the instance object of the external class, the external class object will not be garbage collected, which will also cause memory leaks.

The following content comes from the Internet (the main feature is to empty an element in the stack, not to remove it completely from the array, but to reduce the total number of storage. I can write better than this. When I remove an element, by the way, let it disappear from the array, and set the value of the location of that element to null.)

I really can't think of a more classic example than that stack, so that I have to quote other people's examples. the following example is not what I thought of, but I saw it in a book. of course, if I didn't see it in a book, I might have thought of it myself for a while, but at that time I said it was my own idea and no one believed it.

Public class Stack {private Object [] elements = new Object [10]; private int size = 0; public void push (Object e) {ensureCapacity (); elements [size++] = e;} public Object pop () {if (size = = 0) throw new EmptyStackException (); return elements [--size] } private void ensureCapacity () {if (elements.length = = size) {Object [] oldElements = elements; elements = new Object [2 * elements.length + 1]; System.arraycopy (oldElements, 0, elements, 0, size);}

The above principle should be very simple, if the heap money adds 10 elements, and then all pop up, although the heap money is empty, there is nothing we want, but this is an object that cannot be recycled. This meets the two conditions of memory leak, useless and cannot be recycled. But even if there is such a thing, it will not necessarily lead to any consequences. if this pile of money is used less, it will waste a few K memory. Anyway, our memory is all on G, so what's the impact? besides, this thing will be recycled soon, what does it matter? Let's look at two examples.

Class Bad {public static Stack s = new Stack (); static {s.push (new Object ()); s.pop (); / / there is a memory leak in an object s.push (new Object ()); / / the above object can be recycled, which is equivalent to self-healing}}

Because it is static, it exists until the program exits, but we can also see that it has self-healing function, that is, if your Stack has at most 100 objects, then at most only 100 objects can not be recycled. In fact, this should be easy to understand. Stack holds 100 references, the worst case is that they are useless, because once we put new and enterprising, the previous references naturally disappear!

Another case of memory leak: when an object is stored in the HashSet collection, the fields in the object that participate in calculating the hash value cannot be modified, otherwise, the modified hash value of the object will be different from the hash value originally stored in the HashSet collection, in which case, even if the contains method uses the object's current reference as a parameter to retrieve the object from the HashSet collection The result that the object cannot be found will also be returned, which can also cause the current object cannot be deleted separately from the HashSet collection, resulting in a memory leak.

Attachment: typical cases of memory leaks

(1) temporary memory leaks caused by data structures, see the following code

Public class Stack {private Object [] element=new Object [10]; private int size=0; public void push (Object ele) {ensureCapacity (); element [size++] = ele;} public Object pop () {if (size==0) throw new EmptyStackException (); return element [--size] / / temporarily cause memory leak} private void ensureCapacity () {if (element.length==size) {Object [] oldElement=element; element=new Object [size*2+1]; System.arraycopy (oldElement,0,element,0,size);}

Every time the above code pop (), Stack pops up an element, and before adding a new element, there is actually a reference to element [x] pointing to the popup object, so GC will not garbage collect it. Only making element [x] = newObject when the new element push () makes it possible for previously created objects to be recycled. It would be much safer to change the above pop () method to the following code:

Public Object pop () {if (element.length==size) throws EmptyStackException (); Object o=element [--size]; elements [size] = null; / / gives GC a chance to recycle this object return o;} this is the end of the Java memory leak case analysis. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report