Memory management and memory leaks in Java

Source: Internet
Author: User
Tags object object

Java is now very popular as one of the most popular programming languages on the Internet. Our web applications are primarily developed in the Java language and are broadly divided into three levels of clients, servers, and databases. During the testing process, we found that a program module system memory and CPU resource consumption increased sharply, and continued to grow until java.lang.OutOfMemoryError occurred. The analysis of Java memory leaks is a major factor in destroying the system. Here we share with you the process of detecting and processing Java memory leaks that we have encountered during the development process.

This article first describes the memory management of Java and the causes of Java memory leaks.

I. How Java manages memory

To determine if there is a memory leak in Java, we must first understand how Java manages memory. The memory management of Java is the allocation and release of objects. In Java, the allocation of memory is done by the program, and the release of memory is done by the garbage collector (garbage COLLECTION,GC), the programmer does not need to call the function to free memory, but it can only reclaim the useless and no longer referenced by other objects of the space occupied by those objects.

The memory garbage collection mechanism of Java is to check the reference chain from the main running object of the program, and when it is traversed, it is found that there are no referenced orphaned objects as garbage collection. In order to properly dispose of objects, the GC must monitor the running state of each object, including the application, reference, reference, assignment, etc. of the object, which the GC needs to monitor. The object's state is monitored to release the object more accurately and in a timely manner, and the fundamental principle of releasing the object is that the object is no longer referenced.

In Java, these useless objects are collected by the GC, so programmers do not need to consider this part of the memory leak. Although we have several functions that can access the GC, such as the function System.GC () that runs the GC, the function does not guarantee that the JVM's garbage collector will execute, as defined by the Java language Specification. Because different JVM implementations may use different algorithms to manage the GC. Typically, GC threads have a lower priority level. There are a number of policies that the JVM calls the GC, some of which are used to a certain extent, the GC starts to work, there are timed executions, there is a gentle execution of the GC, and some interrupt-execution GC. But generally speaking, we don't need to care about this.

Two. What is a memory leak in Java

The main reason for a memory leak is that you previously requested a memory space and forgot to release it. If a reference to a useless object exists in the program, those objects will reside in memory and consume memory because the garbage collector GC cannot be verified that the objects are no longer needed. If there is a reference to the object, the object is defined as a "valid activity" and is not freed. To make sure that the object's memory will be recycled, we must make sure that the object is no longer in use. The typical practice is to set the object data member to null or to remove the object from the collection. However, when a local variable is not required, it is not required to be significantly null, because when a method executes, these references are automatically cleaned up.

In Java, the memory leak is the existence of some assigned objects, these objects have the following two characteristics, first of all, these objects are referenced, that is, in a tree diagram, there is a branch path can be connected with, second, these objects are useless, that is, the program will no longer use these objects. If the object satisfies both conditions, these objects can be judged as a memory leak in Java, which is not reclaimed by the GC, but it consumes memory.

Here is a frequently seen example, in the following code, the loop applies to the Object object, and put the requested objects into a vector, if only the object itself, but because the vector still refers to the object, so this object is not recyclable GC. Therefore, if the object has to be removed from the vector after it has been added to the vector, the simplest way is to set the vector object to null.

    1. vector v =  new  vector (10 );      
    2. for  (int i = 1; i < 100; i++)       
    3. {      
    4. object o = < span class= "keyword" >new object ();      
    5. V.add (o);       
    6. o = null;      
    7. }//at this point, all object objects are not freed because the variable v refers to these objects.      

In fact, these objects are already useless, but also referenced, the GC is powerless (in fact, the GC thinks it is useful), which is the most important cause of memory leaks. Then cite another example to illustrate the memory leaks in Java. Suppose there is a log class logger, which provides a static log (String msg), and any other class can call LOGGER.LOG (message) to record the contents of the message into the system's log file.

The logger class has a static variable of type HashMap temp, and each time the log (message) is executed, the value of the message is first written to temp (with the current thread + current time as the key). Delete the entries in temp from the current thread and the current time key before exiting. Note that the current time here is constantly changing, so log execution deletes entries before exiting, and cannot delete entries that were written at the beginning of the execution. Thus, any string passed as a parameter to log will eventually be referenced by the logger static variable temp and cannot be recycled, and this object remains what we call a Java memory leak. In general, memory leaks in memory management are the main reason: object references that remain but are never used again.

Memory management and memory leaks in Java

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.