Android Memory Optimizer 1 understanding Java GC Garbage Collection mechanism 1

Source: Internet
Author: User
Tags compact

The opening crap .

If we want to do the memory optimization work, still need to understand, but this piece of knowledge is purely theoretical, it may seem a bit dull, I try to put this piece of content in accordance with certain logic to go through. First of all, why we should learn the mechanism of garbage collection, I probably summed up a few points:

1.方便我们理解什么样的对象,什么时候,会被系统回收掉2.有助于我们后面的内存优化3.了解这一块的知识也能提升自己的知识广度,和同事一起装逼的时候有话题4.如果有面试的需求的话,了解这一块,也能从容面对考官,对于内存回收能够说出个一二

Well, the nonsense is not much to say, I probably according to the following logic to one one to tell:

1.什么是垃圾回收(GC)2.垃圾回收机制对于我们来说有什么好处?又有什么缺点?3.垃圾回收它是如何工作的?
Technical Details1. What is garbage collection (GC)

Garbage collection or GC (garbage Collection), is an automatic storage management mechanism, it is a major feature of the Java language, it is convenient for us to encode the programmer, the pressure of memory release work is transferred to the system, it is at the cost of consumption system performance. In C + + coding, we need to implement our own destructors for memory release, which is cumbersome and very easy to miss and eventually causes the program to collapse. So the Java language introduces the mechanism of automatic memory management, that is, garbage collection mechanism, for the main memory of the heap area, about the memory allocation mechanism, please check my previous Android Performance Tuning chapter explore JVM memory allocation

2. What are the benefits of the garbage collection mechanism for us? What kind of pits will they bring?

Here's a list of some of the benefits of automatic garbage collection for our system:

1.让作为程序员的我们专注于逻辑实现,提高了我们的编码效率2.能够保护程序的完整性,垃圾回收是Java语言的安全策略的一个重要部分

But with that, there are some drawbacks:

1.系统层面负责垃圾回收,明显会加大系统资源的开销,从而影响程序的性能2.垃圾回收机制也存在不完备性,并不能百分百保证回收所有的垃圾内存
3. Garbage collection How does it work?

In fact, the GC is the main process is: first based on a certain algorithm to determine whether an object is alive, and then the decision is the garbage object to be recycled. In detail, the GC workflow is divided into the following steps:

1.可回收对象的判定2.通过某些算法回收垃圾内存

The next one to tell

1. Determination of Recyclable objects

Our GC needs to reclaim an object, it must be judged whether it is garbage, whether it needs to be recycled, and therefore, each object needs to be recycled.

At present, there are two algorithms on the market to determine whether an object is garbage

1. Reference counting algorithm

This algorithm works by:

1.首先给每一个对象都添加一个引用计数器2.当程序的某一个地方引用了此对象,这个计数器的值就加13.当引用失效的时候(例如超过了作用域),这个计数器就减14.当某一个对象的计数器的值是0的时候,则判定这个对象不可能被使用

This algorithm is simple and efficient for the system, the garbage collector runs faster and does not need to interrupt the execution of our programs for a long time, but the disadvantage is that it is difficult to handle circular references, which makes it impossible to recycle objects that are referenced by each other:

Circular references

I remember that the garbage decision in OC (OBJECTIVE-C) was a reference counting method that referred to a third-party variable to break the balance, but OC did not solve the problem very well and relied more on US developers to deal with it.

2.GC Root Accessibility analysis algorithm

This algorithm works by:

1.以称作“GC Root”的对象作为起点向下搜索2.每走过一个对象,就生成一条引用链3.从根开始到搜索完,生成了一棵引用树,那些到GC Root不可达的对象就是可以回收的

This method obviously solves the problem of circular referencing, but the algorithm is slightly more complex, and here is a diagram of the GC root accessibility algorithm:

Comparison

What we can be used as GC root objects in our program are:

1.虚拟机栈(栈帧中的本地变量表)中引用的对象2.方法区中静态属性引用的对象3.方法区中常量引用的对象4.本地方法栈中JNI引用的对象

Here is a graph to compare the reference counting algorithm with the Accessibility analysis algorithm:

Comparison

Text Description:

1.若使用引用计数算法判定,但图中的C和D对象存在相互引用,导致计数器不为0,无法回收掉2.若使用可达性分析算法,C和D对象到GC Roots 不可达,则能够回收

As for the decision to reclaim objects, we also need to note that when the system starts to start the GC, in order to ensure that the status of the reference chain is not changed, we need to stop all the programs in the process (stop the world), our Android phenomenon is the UI Kaka, But the usual time is very short, of course, if the frequent production of GC, it is another matter.

It is also worth noting that the unreachable object is not immediately recycled, and it takes two of times to mark the process before it is actually recycled:

1.如果对象与GC Root没有连接的引用链,就会被第一次标记,随后判定该对象是否有必要执行finalize()方法2.如果有必要执行finalize()方法,则这个对象就会被放到F-Queue的队列中,稍后由虚拟机建立低优先级的Finalizer线程去执行,但并不承诺等待它运行结束(对象类中能够重写finalize()方法进行自救,但系统最多只能执行一次)3.如果没必要执行finalize()方法,则第二次标记
2. Recovering garbage memory through some algorithms

The above describes how the system determines whether an object is garbage and whether it should be recycled. Then, when the object is determined to be a garbage object, the system will start to recycle, then the system garbage collection algorithm the following several:

1.标记清除算法(Mark-Sweep)2.复制算法(Copying)3.标记整理算法(Mark-Compact)4.分代回收算法

Here are one by one stories

1. Tag cleanup algorithm (mark-sweep)

As the name implies, the algorithm is marked first, then cleared, and it is the two phases of the algorithm: the marking phase and the purge phase to solve:

Mark Clear

Can be seen:

这个算法的优点是易于理解,容易实现,只需要将特定地址的空间进行处理。但缺点也比较明显,把整个内存区域弄得非常不完整,形成了很多碎片化的内存,对于分配大内存的对象时,无法申请足够的空间,从而更多次的触发GC
2. Copy Algorithm (Copying)

The replication algorithm is a solution to the memory fragmentation caused by the markup cleanup algorithm, which is based on the following principles:

Replication Algorithms
1.,复制算法将内存平均分成两个区域A (上)和 B(下)2.将A中的存活的那些对象复制到B区域中3.然后将A区域的所有对象都清除,这样A区域就是一个完整的内存块了,也就避免了内存碎片化了

However, this algorithm also has the obvious disadvantage, that is, regardless of the area of a or B area of the number of surviving objects, the whole block of memory needs to be divided into two regions, which means that the actual memory can be used to become half.

3. Marker grooming Algorithm (mark-compact)

The tagging algorithm is an optimization for marking clearly and works by:

Tag Grooming
1.,第一步也需要进行存活对象的一个标记,这一步与标记清除算法一模一样2.将存活的对象向一端移动,例中是往左上角那一端进行移动3.然后把另一端的内存进行清理

It can also be seen that this algorithm can also avoid the problem of memory fragmentation, but the efficiency is not very good, after all, compared to the replication algorithm, a step more efficient than the same low mark process, and compared with the tag-clearing algorithm, more than one step memory finishing (moving toward the end of the process), significantly lower efficiency.

After all, the world is fair, any algorithm has two sides, we developers can only specific case specific analysis, the use of the most suitable algorithm. Therefore, the algorithm can be seen that the algorithm is suitable for the survival of many objects, the recovery of fewer objects.

4. Generational recovery algorithm

In view of the above three kinds of algorithms have their own shortcomings, and then the great God put forward according to different objects different characteristics, using different algorithms for processing, so strictly speaking is not a new algorithm, but belongs to an algorithm integration scheme, we know:

1.复制算法适用于存活对象少,回收对象多的情况2.标记整理算法适用于存活对象多,回收对象少的情况

The two algorithms are just complementary, so it's perfect to apply these two algorithms to objects of different properties.

Then we should know, which area of the object is what kind of characteristics, according to my previous memory allocation model, heap memory in the new generation has a lot of garbage to be recycled, the old age has little garbage to recycle, then just can be based on this feature using different algorithms for recycling, the specific use of the way:

1.对于新生代区域采用复制算法,因为新生代中每次垃圾回收都要回收大部分对象,那么也就意味着复制次数比较少,因此采用复制算法更高效2.而老年代区域的特点是每次回收都只能回收很少的对象,一般使用的是标记整理或者标记清除算法

In the above way, the whole process of GC has reached the most efficient state.

It is important to note the use of replication algorithms in the generational recovery algorithm.

The previously mentioned replication algorithm is to divide the memory into two, but in the generational recycling is not so, but according to Eden:survivor A:survivor b= 8:1:1, the specific process is (simplified version):

1.新创建一个对象,默认是分在Eden区域,当Eden区域内存不够的时候,会触发一次Minor GC(新生代回收),这次回收将存活的对象放到Survivor A区域,然后新的对象继续放在Eden区域2.再创建一个新的对象,要是Eden区域又不够了,再次触发Minor GC,这个时候会把Eden区域的存活对象以及Survivor A区域的存活的对象移动到Survivor B区域,然后清空Eden区域以及Survivor A区域3.如果继续有新的对象创建,不断触发Minor GC,有些对象就会不断在Survivor A区域以及Survivor B区域来回移动,但移动次数超过15次后,这些对象就会被移动到老年代区域4.如果新的对象在Minor GC后还是放不下,就直接放到老年代5.如果Survivor区域放不下该对象,这直接放到老年代6.如果老年代也满了,就会触发一次Full GC(major gc)
Dry Goods Summary

Through the above, we understand what is a GC, its pros and cons, how it works, the whole process down, the brain also has a GC probability model in the.

This article references the following blogs:

Understanding the Android Java garbage collection mechanism

Java garbage collection mechanism

Master the GC strategy and principles, for our code can avoid some unnecessary memory leaks, we use the Java language to develop, do not blindly go to the pursuit of a variety of good frame or cool business implementation, sometimes, or we need to sink to the heart, a good understanding of the underlying system of some mechanisms, Personally, I think it's necessary.

Android Memory Optimizer 1 understanding Java GC Garbage Collection mechanism 1

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.