In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what will lead to memory leaks in Java". The explanation in this article is simple and clear and easy to learn and understand. Please follow the editor's ideas to study and learn "what will lead to memory leaks in Java".
Concept
Memory leak: refers to the dynamic allocation of memory to some temporary objects in the program, but the objects will not be reclaimed by GC, it always takes up memory, and the allocated objects are reachable but useless. That is, useless objects continue to occupy memory or the memory of useless objects can not be released in time, resulting in a waste of memory space.
Reachability analysis algorithm
JVM uses the reachability analysis algorithm to determine whether the object is alive or not.
GC Root
Through a series of objects named "GC Roots" as the starting point, the search starts from these nodes, and the path of the search is called "Reference Chain". When an object is not connected to the GC Roots, it is proved that the object is not available.
Object4, object5, and object6 judge each other, but they are not reachable to GC Rootd, so they will be determined to be recyclable objects.
The objects that can be used as GC Roots are:
Objects referenced in the virtual machine stack (local variables in stack frames)
Objects referenced by static properties of a class in the method area
Objects referenced by constants in the method area
Objects referenced by JNI in the local method stack
Although Java has a garbage collector to help the group achieve automatic memory management, although GC effectively handles most of the memory, it does not completely guarantee that the memory will not leak.
Memory leak
A memory leak is that objects that are no longer used in heap memory cannot be cleared by the garbage collector, so they exist unnecessarily. This leads to memory consumption, degrades the performance of the system, and ultimately causes OOM to terminate the process.
Performance of memory leaks:
When the application runs continuously for a long time, the performance degrades seriously.
OutOfMemoryError heap errors in applications
Spontaneous and strange application crashes
Applications occasionally run out of connection objects
Possible causes of memory leaks:
1. Memory leak caused by static field
Heavy use of static fields can potentially lead to memory leaks, and in Java, static fields usually have a life cycle that matches the entire application.
Solution: minimize the use of static variables; in singleton mode, rely on delayed loading of objects rather than immediate loading (that is, lazy mode rather than hungry mode)
two。 Unclosed resources cause memory leak
Whenever a connection is created or a stream is opened, JVM allocates memory for these resources. If the connection is not closed, it will cause memory to be occupied continuously. In any case, open connections left by resources consume memory and, if left unhandled, degrade performance, or even OOM.
Solution: use the finally block to close the resource; the code that closes the resource should have no exceptions; after JDK1.7, you can use the too try-with-resource block.
3. Incorrect equals () and hashCode ()
In collections like HashMap and HashSet, equal () and hashCode () are often used to compare objects, and if rewritten improperly, it will become a potential memory leak problem.
Solution: rewrite equals () and hashCode () in the best way.
4. Refers to the inner class of the external class
The initialization of a non-static inner class always requires an instance of an external class; by default, each non-static inner class contains an implicit reference to its external class, and if we use this internal class object in our application, then even after our external class object goes out of scope, it will not be cleared by the garbage collector.
Solution: if the inner class does not need to access the class members contained in the external class, it can be converted to a static class.
5. Memory leak caused by finalize method
When the finalize () method is overridden, the objects of this class are not immediately collected by the garbage collector, and if there is a problem with the code of the finalize () method, it will potentially issue OOM
Solution: avoid overriding the finalize () method.
6. Memory leak caused by constant string
If we read a large String object and call intern (), it will be placed in a string pool, in PermGen, and the string will be retained as long as the application runs, which takes up memory and may result in OOM. (for JDK1.6 and previous, constant pools are in PermGen permanent generations)
Solution: increase the size of the PermGen, and the string pool is transferred to the heap after-XX:MaxPermSize=512M;JDK1.7.
The intern () method is explained in detail:
String str1 = "abc"; String str2 = "abc"; String str3 = new String ("abc"); String str4 = str3.intern (); System.out.println (str1 = = str2); System.out.println (str2 = = str3); System.out.println (str1 = = str4); System.out.println (str3 = = str4); true, false, true, false
The intern () method searches for the string constant pool and returns the specified string if it exists.
Otherwise, the string is put into the constant pool and returned.
In other words, the intern () method ensures that the same string object is returned each time.
String str1 = "abc"; String str2 = "abc"; String str3 = new String ("abcd"); String str4 = str3.intern (); String str5 = "abcd"; System.out.println (str1 = = str2); System.out.println (str2 = = str3); System.out.println (str1 = = str4); System.out.println (str3 = = str4); System.out.println (str4 = = str5); true false true
Why use the intern () method? Look at the source code of the equals method:
Public boolean equals (Object anObject) {if (this = = anObject) {return true;} if (anObject instanceof String) {String anotherString = (String) anObject; int n = value.length; if (n = = anotherString.value.length) {char v1 [] = value; char v2 [] = anotherString.value; int I = 0 While (n return true; -! = 0) {if (v1 [I]! = v2 [I]) return false; iTunes;} return true;}} return false;}
As you can see, when comparing two strings, we first compare whether the two string objects have the same address, and then compare the characters one by one. This greatly speeds up the speed of comparison. Otherwise, it will be very time-consuming to compare one by one each time.
7. Memory leak caused by using ThreadLocal
With ThreadLocal, each thread can keep an implicit call to its copy of the ThreadLocal variable as long as it is alive, and will keep its own copy. Improper use can cause memory leaks.
Once the thread no longer exists, the thread's threadLocal object should be garbage collected, and now the thread is created using a thread pool, which has the function of thread reuse, so the thread will not be reclaimed by the garbage collector. So when you use ThreadLocal to keep a variable copy of a thread in the thread pool, when ThreadLocal is not explicitly deleted, it will remain in memory and will not be garbage collected.
Solution: when you no longer use ThreadLocal, call the remove () method, which removes the current thread value of this variable. Do not use ThreadLocal.set (null), which simply looks for the Map associated with the current thread and sets the value of the threadLocal object in the key value to null, without clearing the key-value pair.
Thank you for reading, the above is the content of "what will lead to memory leaks in Java". After the study of this article, I believe you have a deeper understanding of what will lead to memory leaks in Java, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.