Memory Management for high-performance JAVA code

Source: Internet
Author: User

Even more, the GC cannot be recycled and the system crashes. GC is a program, not intelligent. It only recycles the garbage he thinks, rather than the garbage you think.
GC garbage collection:
Grabage Collection believes that anyone who has learned JAVA knows what this means. But how does it work?
First, when managing the memory, the JVM always divides the variable management into new and old objects. The new object is the developer's new object. However, due to the short life cycle, the memory occupied by the new object is not immediately released, but marked as an old object, at this time, the object still needs to exist for a period of time. Then, the JVM determines whether the object is a spam object and recycles it.
So we can know that the spam memory is not released immediately after it is used up, so the memory is not released in a timely manner, thus reducing the memory usage. When the program is large. This phenomenon is more obvious, and GC also consumes resources. Therefore, memory will be wasted.
Memory reclaim in the life cycle of objects in JVM:
The lifecycle of an object is generally divided into seven stages: creation, application, invisibility, inaccessibility, collection, termination, and release.
Creation phase: Let's take a look at the following two sections of code:
Test1:
For (int I = 0; I <10000; I ++)
Object obj = new Object ();
Test2:
Object obj = null;
For (int I = 0; I <10000; I ++)
Obj = new Object ();
The two pieces of code have the same functions, but it is clear that test2 has better performance than test1, and the memory usage is high. Why? The reason is very simple. test1 creates a temporary Object for each execution of the for loop, but these temporary objects cannot be destroyed immediately due to jvm gc, so they still need to exist for a long time, test2 only saves an object reference in the memory, instead of creating a large number of temporary variables, thus reducing the memory usage.
Do not initialize the same object multiple times. For example:
Public class {
Private Hashtable table = new Hashtable ();
Public A () {table = new Hashtable ();
// This should be removed because the table has been initialized.
}
}
In this way, two Hashtable instances are created, but only one Hashtable instance is used. The other one is ignored because it is not referenced. The memory is wasted. The new operation also affects the code execution speed.
Application phase: This object must have at least one reference during maintenance.
Invisible stage: beyond the scope of the variable. Here is a good practice, because the JVM does not recycle the object immediately during GC, but judges whether the object is being maintained by other references. therefore, if the obj of an object is null or obj after it is used. doSomething () operation. marking it as null can help JVM detect this spam object in time.
Non-reachable phase: direct or indirect reference to this object cannot be found in JVM.
Collection, end, and release phases: When the recycler finds that the object is not reachable, the finalize method has been executed, or the object space has been reused.
JAVA destructor:
Maybe no one believes that JAVA has destructor? Yes, yes. Because all JAVA classes inherit the Object class, and finalize is a method of the Object class, this method in JAVA is similar to the C ++ destructor. in general, objects in the class can be released by reloading the finalize method. for example:
Public class {
Public Object;
Public A () {a = new Object ;}
Protected void finalize () throws java. lang. Throwable {
A = null; // The tag is null and the object is released.
Super. finalize (); // recursively calls the finalize method in the superclass.
}
}
Of course, when is this method called by JVM .......................
In general, we need to create a destory method to explicitly call this method, and then call this method in finalize to implement double insurance.
Because the creation of objects is recursive, that is, the construction of super classes is called first, and then the constructor is called recursively in turn. Therefore, you should avoid initializing variables in the class constructor, this avoids unnecessary memory consumption caused by unnecessary object creation. of course, the advantages of the interface are also shown here.
Array creation:
Given an array length, an array that is too large or too small is often created when you are not sure about the number of data. this causes unnecessary memory waste. Therefore, you can use soft references to tell JVM to recycle the memory in time. (soft reference, details ).
For example:
Object obj = new char [10000000000000000];
SoftReference ref = new SoftReference (obj );
Shared static storage space:
We all know that the memory of static variables is shared during the running of the program. Therefore, sometimes, to save memory, declaring some variables as static variables can indeed save memory space. however, because static variables have a long life cycle and are not easily recycled by the system, it is necessary to use static variables reasonably and not blindly. to avoid backend attacks.
Therefore, it is recommended to use the following conditions:
1. The variable contains a large volume of objects, occupying too much memory.
2. the lifecycle of the object contained in the variable is long.
3. The data contained in the variable is stable.
4. The object instance of this class has the need to share the objects contained in this variable (that is, whether it needs to be used as a global variable ).
Object reuse and GC:
Sometimes, such as database operation objects, we usually need to use them between different modules, so such objects need to be re-used to improve performance. this effectively avoids performance degradation caused by repeated object creation.
In general, the object pool is a good note as follows:
Public abstarct class ObjectPool {
Private Hashtable locked, unlocked;
Private long expirationTime;
Abstract Object create ();
Abstract void expire (Object o );
Abstract void validate (Object o );
Synchronized Object getObject (){...};
Synchronized void freeObject (Object o ){...};
}
In this way, we have completed an object pool. We can use the corresponding methods to access and delete the required objects to maintain this fast memory and improve memory reuse.
Of course, you can also force the System to recycle garbage by calling System. gc (). Of course, the cost is to consume some cpu resources.
Do not create objects in advance:
Try to create objects and allocate them repeatedly when necessary. Constructing objects may reduce performance due to garbage collection.
JVM memory parameter optimization:
Forced memory recovery has a negative impact on the System's automatic memory recovery mechanism and will increase the processing time of the System's automatic recovery. Therefore, avoid explicitly using System. gc (),
JVM settings can improve the system performance. For example:
Java-XX: NewSize = 128 m-XX: MaxNewSize = 128 m-XX: Export vorratio = 8-Xms512m-Xmx512m
For details, refer to the java help documentation. We mainly introduce the performance improvement in programming.
Other experience in memory management in JAVA programming:
According to the working principle of JVM memory management, some techniques and methods can be used to make the JVM more effective in GC processing, so as to improve memory usage and shorten GC execution time.
1. Release reference of useless objects as soon as possible. That is, if it is set to null after the object is not referenced, GC can be accelerated. (Of course, if it is a return value .....)
2. Use the finalize function as little as possible. This function is an opportunity for JAVA to release objects or resources for programmers, but it will increase the GC workload.
3. If you need to use images, you can use the soft application type. It can read images into the memory as much as possible without causing OutOfMemory.
4. Pay attention to the data structure of the collection data type. The more complex the data structure, the more GC workload and the more complicated the processing.
5. Avoid creating in the default constructor (constructor) and initializing a large number of objects.
6. Try to avoid forcing the system to perform garbage collection, which will increase the final time for the system to perform garbage collection to reduce performance.
7. Avoid explicitly applying for an array. If you have to apply for an array, estimate the array size as accurately as possible.
8. If you are calling a remote method, try to reduce the size of the passed object or use an instantaneous value to avoid unnecessary data transmission.
9. Use the object pool to improve system performance and reduce memory overhead when appropriate. Of course, the object pool cannot be too large and will be counterproductive.

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.