Turn to an article on Java Memory leakage (Benefit)

Source: Internet
Author: User
Http://www.lybbs.net/news_read.do? Newspath = 2007/9/25/1190684628458 .html
 

1 Introduction
An important advantage of Java is that the Garbage Collector GC (garbage collection) automatically manages memory collection. programmers do not need to call functions to release the memory. Therefore, many Programmers think that Java does not have a memory leak problem, or that even memory leaks are not the responsibility of the program, but GC or JVM problems. In fact, this idea is incorrect, Because Java also has memory leakage, but its performance is different from that of C ++. If the Java code being developed runs on the server 24 hours a day, the impact of memory vulnerabilities on the server is much greater than that on the configuration utility, even with the smallest vulnerability, the JVM consumes all available memory. In addition, in many embedded systems, the total amount of memory is very limited. On the contrary, even if the program has a short lifetime, if there is any Java code that allocates a large number of temporary objects (or a number of objects that consume a large amount of memory, in addition, when these objects are no longer needed and their references are not canceled, the memory limit may still be reached.

2 Java memory recovery mechanism
Java memory management is the issue of object allocation and release. Memory Allocation varies depending on the syntax structure of the language. However, no matter which language is used for memory allocation, the initial address of the allocated memory block is returned, that is, a pointer to the first address of the memory block. In Java, all objects are allocated in heap. objects are created in the new or reflection mode, but objects are released directly, therefore, the collection of objects is completed by the Java Virtual Machine through the garbage collector. This two-line approach simplifies the programmer's work, but also increases the JVM's work, which is also one of the reasons for the slow Java program running. To release objects correctly, GC must monitor the running status of each object, including application, reference, reference, and assignment of objects. GC must monitor all objects. The object state is monitored to release objects more accurately and timely. The fundamental principle of releasing objects is that the object is no longer
Referenced. Java uses Directed Graphs for memory management to eliminate the issue of reference loops. For example, if there are three objects that are referenced by each other, as long as they are inaccessible to the root process, GC can also recycle them. In Java, there are only two criteria for determining whether a piece of memory space meets the collection standard of the garbage collector: one is to assign null values to the object, and the following has not been called, the other is to assign a new value to the object, that is, re-allocate the memory space.

3. Memory leakage in Java

3.1 differences between memory leakage and C ++ in Java
In Java, memory leakage is the existence of some allocated objects. These objects have the following two features: first, these objects are reachable, that is, in a directed graph, there are paths that can be connected to them; second, these objects are useless, that is, they will not be used by the program in the future. If the objects meet these two conditions, these objects can be identified as memory leaks in Java. These objects are not recycled by GC, but occupy the memory. In C ++, the memory leakage scope is larger. Some objects are allocated with memory space, but they are not reachable. Because c ++ does not have GC, these memories will always be charged.
No. In Java, GC is responsible for the collection of these inaccessible objects, so programmers do not need to consider this part of Memory leakage. Through analysis, we can know that for C ++, programmers need to manage their own edges and vertices, while for Java programmers, they only need to manage edges (no need to manage vertices ).
). In this way, Java improves programming efficiency.

3.2 Memory leakage example
3.2.1 Example 1
In this example, the object is applied cyclically and put into a vector. If only the reference itself is released, the vector still references the object, therefore, this object cannot be recycled for GC. Therefore, if an object is added to a vector, it must be deleted from the vector. The simplest way is to set the vector object to null.
Vector v = new vector (10 );
For (INT I = 1; I <100; I ++)
{Object o = new object ();
V. Add (O );
O = NULL;
}//

At this time, all object objects are not released because variable v references these objects. Actually useless, and the referenced object, GC is powerless (in fact, GC thinks it is still useful), which is the most important cause of Memory leakage.

(1) If you want to release an object, you must set its reference count to 0. Only those objects that are no longer referenced can be released. This principle is very simple, but it is very important, it is the basic cause of Memory leakage and the purpose of solving the memory leakage;
(2) The programmer does not need to manage the specific allocation and release process of the object space, but must pay attention to whether the reference count of the released object is 0;
(3) process in which an object may be referenced by other objects:
A. assign values directly. In the example above, A. A = E;
B. Pass the parameter, for example, public void addobject (Object E );
C. Other situations such as system calls.

3.3 causes of Memory leakage
3.3.1 static collection class
Static collection classes such as hashmap and vector are most likely to cause memory leakage because the lifecycle of these static variables is consistent with that of the application. For example, if the vector is static, it will always exist, and all the object objects in it cannot be released because they will also be referenced by the vector.
3.3.2 listener
In Java programming, we all need to deal with listeners. Generally, many listeners are used in an application. We will call methods of controls such as addxxxlistener () to increase listeners, however, when releasing objects, you often do not remember to delete these listeners, which increases the chance of Memory leakage.
3.3.3 physical connection
Some physical connections, such as database connections and network connections, will not be automatically recycled by GC unless the connection is explicitly closed. Java database connections are generally created using datasource. getconnection (). When they are no longer used, they must be released using the close () method because these connections are independent of JVM. The resultset and statement objects can be explicitly recycled, but the connection must be explicitly recycled, because the connection cannot be automatically recycled at any time, and once the connection is recycled, the resultset and statement objects are immediately null. However, if you use a connection pool, the situation will be different. In addition to explicitly closing the connection, you must also explicitly close the resultset statement object (close one of them, and the other will also close ), otherwise, a large number of statement objects cannot be released, causing memory leakage.

3.3.4 reference of internal classes and external modules
The reference of internal classes is relatively easy to forget, and once not released, a series of subsequent class objects may not be released. For programmers, their programs know that if memory leaks are found, their reference to these objects can be quickly located and resolved, but the current application software
It is not implemented by one person. The idea of modularization is very obvious in modern software, so programmers should be careful with the casual reference of external modules. For example, programmer A is responsible for module A and calls a method of Module B, for example:
Public void registermsg (object B );
This kind of call should be very careful. If an object is passed in, it is very likely that Module B maintains the reference to this object. At this time, you need to pay attention to whether Module B provides the corresponding operation to remove the reference.

4. prevent and detect memory Vulnerabilities
After learning about some causes of Memory leakage, we should try our best to avoid and detect memory leakage.
(1) Good coding habits. The most basic suggestion is to release reference of useless objects as soon as possible. When using temporary variables, most programmers automatically set the reference variables to null after they exit the active domain. When using this method, you must pay special attention to some complex object graphs, such as arrays, columns, trees, and graphs. These objects have more complex reference relationships. For such objects, GC is generally less efficient to recycle them. If the program permits it, assign null to unnecessary reference objects as soon as possible. Other suggestions:
After confirming that an object is useless, explicitly set all its references to NULL;
When the class is inherited from the jpanel, jdialog, or other container classes, call the removeall () method before deleting the object. Before setting a reference variable to a null value, check whether the object pointed to by the referenced variable is listened on. If yes, remove the listener before assigning null values. When the object is a thread, before deleting this object, you may wish to call its interrupt () method. In the memory detection process, you should not only pay attention to the class objects you write, but also pay attention to some basic types of objects, such: int [], String, char [], etc. If a database connection exists, use try... finally structure. Close the statement object and connection in finally.
(2) Good test tools. Memory leakage cannot be completely avoided during development. The key is to use a good test tool to quickly locate the problem when detecting Memory leakage. There are already several professional Java memory leak check tools on the market. Their basic working principles are similar. They are all through monitoring the application, release, and other actions of all objects when Java programs are running, collects, analyzes, and visualizes all memory management information. Based on this information, developers will determine whether the program has a memory leakage problem. These tools include optimizeit profiler, Jprobe Profiler, jinsight, and purify of rational.

Note:
An image (reflector) is a program's ability to analyze itself. The Java. Lang. Reflect package provides the ability to obtain information about field, constructor, method, and class modifiers. You can use this information to create a tool for dealing with Java Beans components. You can dynamically create features of a component.
Heap: Both stack and heap are places where Java is used to store data in Ram. Unlike C ++, Java automatically manages stacks and stacks, and programmers cannot directly set stacks or stacks. The advantage of stack is that the access speed is faster than the heap speed, second only to the registers directly in the CPU. However, the disadvantage is that the data size and lifetime in the stack must be fixed, and there is a lack of flexibility. In addition, stack data can be shared. The advantage of the heap is that the memory size can be dynamically allocated and the lifetime does not have to be told to the compiler in advance. The Java garbage collector will automatically collect the unused data. However, the slow access speed is due to the need to dynamically allocate memory during runtime.
Connection Pool: in actual application development, especially in Web application systems, If JSP, Servlet, or EJB uses JDBC to directly access data in the database, every data access request must go through the steps of establishing a database connection, opening a database, accessing data, and closing a database connection. Connecting to and opening a database is a resource-consuming and time-consuming task, if such database operations occur frequently, the system performance will inevitably drop sharply, and even cause the system to crash. The database connection pool technology is the most commonly used method to solve this problem. In many application servers (such as WebLogic, websphere, and JBoss), this technology is basically provided and does not need to be programmed by yourself, however, it is necessary to gain an in-depth understanding of this technology.
The idea of database connection pool technology is very simple. database connections are stored as objects in a vector object. Once a database connection is established, different database access requests can share these connections, by reusing these established database connections, you can overcome these shortcomings and greatly save system resources and time.
The main operations of the database connection pool are as follows:
(1) Create a database connection pool object (server startup ).
(2) create an initial number of database connections (idle connections) based on the specified parameters ).
(3) For a database access request, a connection is directly obtained from the connection pool. If there is no idle connection in the database connection pool object and the number of connections does not reach the maximum (that is, the maximum number of active connections), create a new database connection.
(4) access the database.
(5) Close the database and release all database connections (close the database connection at this time, rather than actually close it, but put it into the idle queue. If the actual number of idle connections is greater than the initial number of idle connections, the connection is released ).
(6) release the database connection pool object (during server stop and maintenance, release the database connection pool object and release all connections ).

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.