To be a stingy Java programmer--a GC-oriented programming __ algorithm

Source: Internet
Author: User

Source Link: Bat through train--to be a stingy Java programmer--oriented to the GC programming

PS: Welcome to the bat through train to get the latest experience of bat old driver foreword

It's much easier to develop Java development than C + +, because programmers don't have to care about trick memory issues. The highly optimized GC mechanism of the JVM ensures that in most cases the system is able to handle memory problems well. But rely entirely on GC, programming does not pay attention to the relevant use details, the program is often not the ideal performance, so to do a stingy Java programmer, the programming time to think about memory, garbage collection related points, help improve the performance of the program. Here is a list of the points that are often considered at work. 1. Container initialization To specify the size of

See most of the program in the use of containers, StringBuilder, StringBuffer is directly used, did not specify the initial size, this is a rookie embodiment. From the memory, garbage collection point of view, these containers and classes must be given the initial size when used.

It is because the above mentioned containers, classes can be dynamically extended, so we usually do not consider setting the initial size, anyway, will automatically expand.

But there is a price for expansion, and there is a high cost of memory. Most of the expansion is done by copy, the old data is added to the new structure after the expansion, for the continuous expansion of the situation, will produce a large number of useless old arrays, these arrays occupy memory, but also increase the pressure of the GC. This is often the case with memory jitter that is more severe.

Therefore, it is recommended to add the pre estimate of capacity in the constructor when using these containers and classes. 2. Use less ugly references to null method

Most of the time, we'll see someone who is really a GC-oriented program, which is really useful if the object is null after it is not used.

List<myobject> alist = new arraylist<myobject> ();
....
...
Alist = null;

Mybigobject  myobj = new Mybigobject ();
...
myobj = null;

The answer is that in most cases this is useless and will only make your code uglier.

In fact, the GC is far more intelligent than you think, and the benefits are minimal, and the GC will detect the unwanted object itself.

But if it's in a larger method, this approach can be very long (expanding the hundreds of-line method, which is sometimes common), and is time-consuming to execute, which in some cases can help by putting some large unused objects to null in advance. 3. Use object pool with caution

While looking at some code optimizations, it is found that many people use object pooling for reuse optimization. This is a good starting point for improving performance by reducing the allocation overhead of an object. But the disadvantage is that because objects in the object pool will survive for a long time, most objects will be promoted to old Generation and therefore cannot be recycled through YOUNGGC.

For the use of object pools, if the object itself is small and the initialization overhead is not large, then the object pool will only increase the complexity of the code, which is typically over optimized. If it happens that the object itself is relatively large, then the promotion to the old generation, the pressure on the GC is even greater. Again from the point of view of thread safety, in general, the pool will be concurrent access, if the object pool does not handle concurrency problems, then the system or application to face the corresponding problems. However, there is also overhead in processing thread synchronization, so consider the overhead of thread synchronization and the cost of object creation.

The most reasonable scenario for using object pooling is when the cost of creating an object is relatively high, for example:

Network link
database link
thread creation
4. Does the manual GC really make sense?

You can often see two lines of code

Thread.yield ()
System.GC ();

The former is the initiative to give up the CPU resources, the latter is the active trigger GC, but it really works.

in fact, the JVM is guaranteeing the two things ...

What's more, if an explicit GC is allowed in the JVM startup parameters, the trigger is FULLGC, yes, you're right, and FULLGC,FULLGC means stop the world!!!, which is a downtime for certain response time demanding applications ....

So, our conclusion is: Do not use Thread.yield () do not use System.GC (), but native memory GC except

* * Note: **native memory can only be recycled through the FULLGC or CMS GC, unless you know exactly when to call and know the consequences, you can call System.GC (). When you use a byte buffer like a directbytebuffer partition NiO or a NIO framework (such as Netty), use Mappedbytebuffer to do memory mapping

These situations will use more native Memory, and manual triggering should be prudent. For security reasons, it is best to add-XX:+DISABLEEXPLICITGC to the JVM's startup parameters to disable the explicit GC, but there is a paradox that if System.GC () is disabled, the native memory mentioned above cannot be recycled. So developers in the use of the time to consider comprehensive, and the line and cherish. 5. Focus on the scope of objects, properties

From the garbage collection point of view, try to make the declaration period of the object shorter, as much as possible to shorten the scope of the object. Please follow the following recommendations:

If you can declare local variables within a method, do not declare them as instance variables.
declare the static variable as little as possible unless your object is single or invariant.

Local variables are reclaimed by GC after the method is executed, so precedence is given to the life cycle of the variable before the variable is defined.

Static variables are in a constant pool, and garbage collection does not handle constant pools, so define constants as little as possible. 6. Caching and referencing

If you want to implement the cache, it is best not to HashMap or concurrenthashmap, for weak reference weakhashmap, preferably using a caching framework, guava cache relatively good, recommended. 7. Summary

The 6 points mentioned above are common empirical summaries of practical work, there may not be much improvement in different scenarios, but familiarity with these methods, thinking about programs from the perspective of JVM memory and garbage collection, is essential for writing excellent code, and the Java road is long and well cherished.

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.