How to write a piece of code in Java to cause memory leakage

Source: Internet
Author: User
Tags deflater

How to write a piece of code in Java to cause memory leakage

Q:I attended the interview just now. The interviewer asked me how to write the Java code with Memory leakage. I have no idea at all about this problem.

A1:The following steps make it easy to cause memory leakage. program code cannot access some objects, but they are still stored in the memory ):

Because there is no reference to classes and class loaders, the storage in ThreadLocal cannot be accessed. ThreadLocal holds the reference of this object, and it also holds the reference of this class and Its Class Loader. The class loader holds all references of the class it loads, in this way, GC cannot recycle the memory stored in ThreadLocal. In many JVM implementations, Java classes and class loaders are directly allocated to the permgen region without performing GC, which leads to more serious memory leakage.

One of the variants of this leak mode is that if you often redeploy applications that use ThreadLocal, application containers such as Tomcat in any form) memory leakage may occur easily because the application container uses the thread as described above, the new class loader will be used each time the application is redeployed ).

A2:

Static variable reference object

Class MemorableClass {
Static final ArrayList list = new ArrayList (100 );
}

Call a long stringString.intern()

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 stream (file, network, etc.) 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 ();
}

Jvm gc inaccessible region

For example, the native method is used to allocate memory.

Objects of the web application in the application scope. The application has not been restarted or is not explicitly removed.

getServletContext().setAttribute("SOME_MAP", map);

Objects of the web application in the session range are not invalid or are not explicitly removed.

session.setAttribute("SOME_MAP", map);

Incorrect or inappropriate JVM options

For example, the noclassgc of the ibm jdk prevents garbage collection of useless classes.

A3:If HashSet is not correctly implemented (or not implemented)hashCode()Orequals(), Which will lead to the continuous addition of "copies" in the collection ". If a set cannot ignore the elements that it should ignore, its size can only grow continuously and cannot be deleted.

If you want to generate an incorrect key-value pair, do the following:

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 the forgotten listeners, static references, key errors, modifications, or thread blocking in hashmap, and other typical Memory leakage scenarios, the following describes some of the less obvious cases of Memory leakage in Java, mainly thread-related.

  • Runtime. addShutdownHook is not removed. Even if removeshudownhook is used, it may not be recycled due to the bug of ThreadGroup for threads not started, resulting in Memory leakage of ThreadGroup.
  • The thread is created but not started, which is the same as the preceding scenario.
  • Create a thread that inherits ContextClassLoader and AccessControlContext, use ThreadGroup and InheritedThreadLocal, all of which are potential leaks, and all classes loaded by the class loader and all static references. This has a significant impact on the entire j. u. c. Executor framework (java. util. concurrent) as an important component of the ThreadFactory interface. Many developers have not noticed its potential risks. In addition, many libraries start threads according to requests.
  • ThreadLocal cache, which is not a good practice in many cases. There are many simple cache implementations based on ThreadLocal, but if the thread continues to run ContextClassLoader beyond its expected life cycle, it will be leaked. Unless necessary, do not use ThreadLocal cache.
  • ThreadGroup. destroy () is called when ThreadGroup itself does not have threads but there are still sub-thread groups (). The thread group cannot be removed from its parent thread group due to memory leakage, and the sub-thread group cannot be enumerated.
  • Using WeakHashMap and value directly (indirectly) reference the key is difficult to find. This also applies to classes that inherit Weak/SoftReference may hold strong references to protected objects.
  • Use java.net. URL of http (s) to download resources. KeepAliveCache creates a new thread in the system ThreadGroup, causing memory leakage of the context class loader of the current thread. When no surviving thread exists, the thread is created in the first request, so leakage is likely to occur. (It has been corrected in Java 7, and the context class loader is reasonably removed from the Code of the thread creation .)
  • Use InflaterInputStream to pass new java.util.zip. Inflater () in the constructor (such as PNGImageDecoder) without calling inflater end (). It is safe only for new, but if you create this class as the constructor parameter, the close () of the called stream cannot close inflater, and memory leakage may occur. This is not a real memory leak because it will be released by finalizer. However, this consumes a lot of native memory, causing linux oom_killer to kill the process. So the lesson is to release native Resources as early as possible.
  • The same is true for java.util.zip. Deflater, which is more serious. The good thing is that Deflater is rarely used. If you have created Deflater or Inflater, remember to call end ().

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.