Java memory leak cause resolution

Source: Internet
Author: User
Tags connection pooling object object

1 Introduction

An important advantage of Java is that the garbage collector GC (Garbage Collection) automatically manages the recycling of memory, and programmers do not need to invoke functions to free memory. Therefore, many programmers think that Java does not have a memory leak problem, or even if there is a memory leak is not the responsibility of the program, but the problem of GC or JVM. In fact, this idea is incorrect, because Java also has a memory leak, but it behaves differently from C + +. If the Java code being developed is to run on the server 24 hours a day, the impact of a memory vulnerability here is much greater than in the configuration utility, even if the smallest vulnerability causes the JVM to run out of all available memory. In addition, in many embedded systems, the total amount of memory is very limited. In the opposite case, even if the lifetime of the program is short, if there are any Java code that allocates a large number of temporary objects (or several objects that devour large amounts of memory), and if they are no longer needed, then the memory limit may still be reached.

2 Java Memory Recovery mechanism

The memory management of Java is the allocation and release of objects. Memory is allocated in a variety of ways, depending on the grammatical structure of the language. However, regardless of which language the memory allocation method, and finally to return the allocated memory block of the starting address, that is, return a pointer to the first address of the memory block. In Java, where all objects are allocated in the heap, the creation of objects is usually in the form of new or reflected, but the object is freed with a direct means, so the collection of objects is done by the Java virtual machine through the garbage collector. This two-line approach does simplify the programmer's work, but it also adds to the JVM's work, which is one of the reasons why the Java program is running slower. Because, in order for the GC 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
Be referenced. Java uses a graph-like approach to memory management, which eliminates the problem of reference loops, such as having three objects and referencing each other, so that GC can reclaim them as long as they and the root process are unreachable. In the Java language, there are only two criteria to determine whether a piece of memory space conforms to the garbage collector's collection criteria: one is to give the object null value, the following is not called, and the other is to give the object a new value, that is, to reallocate memory space.

3 memory leaks in Java

3.1 The difference between memory leaks and C + + in Java

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 accessible, that is, in the graph, the existence of the path can be connected to it, and secondly, 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. In C + +, memory leaks are larger in scope. Some objects are allocated memory space, and then unreachable, because there is no GC in C + +, these memory will always be
Not come back. In Java, these unreachable objects are collected by the GC, so programmers do not need to consider this part of the memory leak. From the analysis, it can be learned that for C + +, programmers need to manage their own edges and vertices, and for Java programmers only need to manage the edge (do not need to manage the vertex
Release). In this way, Java improves the efficiency of programming.

3.2 Memory Leak Example

3.2.1 Example 1
In this example, the loop applies to the Object object and puts the requested objects into a vector, and if you just release the reference itself, then the vector still references the object, so the object is not recyclable to the 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.
Vector v = new vector (10);
for (int i = 1; i<100; i++)
{Object o = new Object ();
V.add (o);
o = null;
}//

At this point, all object objects are not freed because the variable v refers to these objects. The GC is powerless (in fact, the GC considers it useful), which is the most important cause of a memory leak, which is actually useless and is still being referenced.

(1) If you want to release the object, you must make its reference count of 0, only those objects that are no longer referenced can be freed, this principle is very simple, but very important, is the basic cause of memory leaks, but also the purpose of resolving the memory leak method;
(2) The programmer does not need to manage the object space specific allocation and release process, but must pay attention to the released object's reference count is 0;
(3) A few of the procedures that an object may be referenced by another object:
A. Direct assignment, as in the above example A.A = E;
B. Pass through parameters, such as public void AddObject (Object E);
C. Other situations, such as system calls.

3.3 Reasons why memory leaks are easy to cause

3.3.1 static Collection Class
The use of static collection classes like HashMap, vectors, etc. is most likely to cause a memory leak because the lifetime of these static variables is consistent with the application, such as Example 1, if the Vector is static, Then it will always exist, and all of the object objects will not be freed, as they are also always referenced by the vector.
3.3.2 listener
In Java programming, we all need to deal with listeners, usually one application will use a lot of listeners, we will call a control such as Addxxxlistener () and other methods to increase the listener, However, it is often not remembered to remove these listeners when releasing objects, thus increasing the chance of memory leaks.
3.3.3 Physical Connection
Some physical connections, such as database connections and network connections, are not automatically reclaimed by GC unless they explicitly close the connection. Java database connections are typically created with datasource.getconnection (), which must be freed with the close () method when they are no longer in use, because these connections are independent of the JVM. For Resultset and statement objects can not be explicitly recycled, but connection must be explicitly recycled, because connection can not be automatically recycled at any time, and connection once recycled, Resultset And the statement object are immediately null. However, if you use connection pooling, the situation is different, in addition to explicitly closing the connection, you must also explicitly close the ResultSet Statement object (Close one, the other will also shut down), otherwise it will cause a large number of Statement objects can not be released, causing a memory leak.

3.3.4 references to internal classes and external modules, etc.
The reference to the inner class is a relatively easy one to forget, and once it is not released it can cause a series of subsequent class objects not to be released. For programmers, their programs are clear that if a memory leak is found, their references to these objects can be quickly located and resolved, but now the application software
Not a person to achieve, modular thinking in modern software is very obvious, so the programmer should be careful of external modules inadvertently reference, such as programmer A is responsible for the A module, a method called the B module, such as:
public void registermsg (Object b);
This call will be very careful, passing in an object, it is likely that module B will maintain a reference to the object, it is important to note that Module B provides the appropriate action to remove the reference.

4 Preventing and detecting memory leaks

When you understand some of the causes of memory leaks, you should avoid and discover memory leaks as much as possible.
(1) Good coding habits. The most basic suggestion is to release the reference to the useless object as soon as possible, and most programmers use the temporary variable to have the reference variable automatically set to null after exiting the active domain. In this way, it is important to pay special attention to complex object graphs, such as arrays, columns, trees, graphs, and so on, which are more complex to refer to each other. For such objects, GC recycling is generally less efficient. If the program allows, the unused reference object will be assigned null as soon as possible. Another suggested points:
After confirming that an object is useless, explicitly set all its references to null;
When a class inherits from JPanel or JDialog or other container classes, it is advisable to call its RemoveAll () method before deleting the object, and before setting a reference variable to a null value, you should be aware that the object to which the reference variable is directed is being monitored, and if so, to remove the listener first, You can then assign a null value, and when the object is a thread, you might want to call its interrupt () method before deleting the object, while the memory detection process should focus not only on the class objects you write, but also on some basic types of objects, such as: int[], String, char[ ] and so on; If you have a database connection, use the try...finally structure to close the statement object and the connection in finally.
(2) a good test tool. In the development of the memory leak can not be completely avoided, the key is to find a memory leak when the use of good testing tools to quickly locate the problem. There are several professional tools on the market to check the Java memory leaks, they basically work the same principle, all through the monitoring of the Java program runtime, all object application, release and other actions, the memory management of all the information to statistical, analysis, visualization. The developer will use this information to determine if the program has a memory leak problem. These tools include Optimizeit Profiler, JProbe Profiler, JinSight, Rational company Purify, and more.

Remember:
Image (Reflector) is the ability of a program to analyze itself. The Java.lang.reflect package provides the ability to get information about the modifiers of fields, constructors, methods, and classes. This information can be used to create tools for dealing with Java beans components. You can create the characteristics of a component dynamically.
Heap: The Stack and heap (heap) are places where Java is used to store data in RAM. Unlike C + +, Java automatically manages stacks and heaps, and programmers cannot directly set up stacks or heaps. The advantage of the stack is that the access speed is faster than the heap, second only to the registers directly in the CPU. However, the disadvantage is that the size and lifetime of the data in the stack must be deterministic and inflexible. In addition, the stack data can be shared, the advantage of the heap is the ability to dynamically allocate memory size, the lifetime does not have to tell the compiler beforehand, the Java garbage collector will automatically take away the data that is no longer used. However, the disadvantage is that the access speed is slower due to the dynamic allocation of memory at run time.
Connection pooling: In real-world application development, especially in Web applications, if a JSP, servlet, or EJB uses JDBC to directly access data in a database, every data access request must undergo steps such as establishing a database connection, opening a database, accessing data, and shutting down a database connection. While connecting and opening the database is a resource consuming and time consuming work, if this kind of database operation occurs frequently, the performance of the system will inevitably drop sharply, even cause the system to crash. Database connection pooling technology is the most common method of solving this problem, and in many application servers (for example: Weblogic,websphere,jboss), it is essential to provide this technology without having to program it yourself, but it is essential to understand the technology in depth.
Database connection pooling Technology The idea is very simple, the database connection as an object stored in a vector object, once the database connection is established, the different database access requests can share these connections, so that through the reuse of these established database connections can overcome the above shortcomings, Significant savings in system resources and time.
The main operations of the database connection pool are as follows:
(1) Establish database connection pool object (server start).
(2) Create the initial number of database connections (that is, the number of idle connections) according to the parameters specified beforehand.
(3) For a database access request, get a connection directly from the connection pool. Create a new database connection 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).
(4) Access the database.
(5) Close the database, release all database connections (at this point, close the database connection, not really shut down, but put it in an idle queue.) Release the connection if the number of actual idle connections is greater than the number of initial idle connections).
(6) Release the database connection pool object (during server stop, maintenance, release the database connection pool object, and release all connections).

Original address:
Http://www.cnblogs.com/dotnetdoor/archive/2008/06/09/1216125.html

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java memory leak cause resolution

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.