In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Today, I will talk to you about how to write a piece of code in Java that causes memory leaks. Many people may not know much about it. In order to make you understand better, the editor has summarized the following contents for you. I hope you can get something according to this article.
Q: just now I attended the interview and the interviewer asked me how to write the Java code that would cause a memory leak. I have no idea about this question at all. It's embarrassing.
A1: memory leaks can easily occur by following these steps (some objects cannot be accessed by program code, but they are still kept in memory):
The application creates a long-running thread (or uses a thread pool for faster memory leaks).
A thread loads a class through a class loader that can be customized.
This class allocates large chunks of memory (such as new byte [1000000]), stores a strong reference in a static variable, and then stores its own reference in ThreadLocal. Allocating additional memory new byte [1000000] is optional (class instance leaks are sufficient), but this makes memory leaks faster.
The thread cleans up the custom class or loads the class loader for that class.
Repeat the above steps.
Without references to classes and class loaders, the storage in ThreadLocal cannot be accessed. ThreadLocal holds a reference to the object, it holds references to the class and its classloader, and the classloader holds all references to the class it loads, so GC cannot reclaim memory stored in ThreadLocal. In many JVM implementations, Java classes and class loaders are allocated directly to the permgen region without performing GC, which leads to more serious memory leaks.
One of the variants of this leak pattern is that if you often redeploy applications that use ThreadLocal in any form, application containers (such as Tomcat) are prone to memory leaks (because the application container uses the threads described earlier, a new classloader will be used each time the application is redeployed).
A2:
Static variable reference object
Class MemorableClass {
Static final ArrayList list = new ArrayList
}
Call String.intern () of a long string
String str=readString (); / / read lengthy string any source db,textbox/jsp etc..
/ / This will place the string in memory pool from which you cant remove
Str.intern ()
Open streams (files, networks, etc.) are not closed
Try {
BufferedReader br = new BufferedReader (new FileReader (inputFile))
...
...
} catch (Exception e) {
E.printStacktrace ()
}
Connection not closed
Try {
Connection conn = ConnectionFactory.getConnection ()
...
...
} catch (Exception e) {
E.printStacktrace ()
}
GC unreachable region of JVM
For example, memory allocated through the native method.
Web applies to application-scoped objects that are not restarted or explicitly removed
GetServletContext () .setAttribute (SOME_MAP, map)
Objects applied by web to the scope of session, not invalidated or not explicitly removed
Session.setAttribute ("SOME_MAP", map)
Incorrect or inappropriate JVM options
For example, IBM JDK's noclassgc prevents garbage collection of useless classes.
A3: if HashSet does not implement (or does not implement) hashCode () or equals () correctly, it will result in a continuous increase of "copies" in the collection. If the collection cannot ignore the elements it should ignore, its size can only continue to grow, and these elements cannot be deleted.
If you want to generate the wrong key-value pair, you can do something like this:
Class BadKey {
/ / no hashCode or equals ()
Public final String key
Public BadKey (String key) {this.key = key;}
}
Map map = System.getProperties ()
Map.put (new BadKey ("key"), "value") / / Memory leak even if your threads die.
A4: in addition to typical memory leak scenarios such as forgotten listeners, static references, key errors / modifications in hashmap or thread blocking can not end the life cycle, here are some less obvious cases of memory leaks in Java, mainly thread-related.
Runtime.addShutdownHook is not removed, even if removeShutdownHook is used, because the ThreadGroup class may not be recycled for the bug of the unstarted thread, resulting in a memory leak in the ThreadGroup.
Create but not start a thread, as in the case above
Creating threads that inherit ContextClassLoader and AccessControlContext, the use of ThreadGroup and InheritedThreadLocal, all these references are potential leaks, and all classes and all static references loaded by the class loader, and so on. The impact on the ThreadFactory interface as an important component of the entire j.u.c.Executor framework (java.util.concurrent) is so obvious that many developers are unaware of its potential dangers. And many libraries start threads on request.
ThreadLocal caching is not a good practice in many cases. There are many implementations of simple caching based on ThreadLocal, but a leak will occur if a thread continues to run ContextClassLoader outside its expected life cycle. Do not use ThreadLocal caching unless it is really necessary.
ThreadGroup.destroy () is called when ThreadGroup itself does not have a thread but still has a subthread group. A memory leak will prevent the thread group from being removed from its parent thread group and enumerating child thread groups.
Using WeakHashMap,value to reference key directly (indirectly) is a difficult situation to find. This also applies to classes that inherit Weak/SoftReference that may hold strong references to protected objects.
Download resources using java.net.URL of the http (s) protocol. KeepAliveCache creates a new thread in the system ThreadGroup, causing the current thread's context class loader memory leak. When there is no viable thread, the thread is created on * requests, so a leak is likely to occur. (it has been fixed in Java7 that the code that creates the thread has reasonably removed the context class loader.)
Use InflaterInputStream to pass new java.util.zip.Inflater () in a constructor, such as PNGImageDecoder, without calling inflater's end (). New alone is very safe, but if the close () of the call stream cannot close inflater when you create this class as a constructor parameter, a memory leak can occur. This is not a real memory leak because it will be freed by finalizer. But this consumes a lot of native memory, causing linux's oom_killer to kill the process. So the lesson is: release native resources as early as possible.
The same is true of java.util.zip.Deflater, whose situation is even more serious. The good place may be that Deflater is rarely used. If you create Deflater or Inflater, remember that you must call end ().
After reading the above, do you have any further understanding of how to write a piece of code in Java to cause a memory leak? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.
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.