The garbage collection mechanism inside Flash Player and Adobe AIR

Source: Internet
Author: User

Read notes:

· Required knowledge
This article is written for middle and senior as developers and requires readers to have a moderate understanding of the concept of object-oriented programming and as3 development.

· Reader level:
Moderate level.

· Required software:
Flash Builder (download trial)
Flash Professional (download trial)

All applications need to manage memory. The memory management system of an application includes the following principles: When to distribute memory, how much memory to distribute, and when to put things in the recycle bin, and when to clear the recycle bin. Mmgc is a general memory manager for almost all memory allocations of Flash Player. It is important to know how mmgc manages memory and optimize your code and run programs.

The mechanism for memory garbage collection is called "managed memory ". The garbage collection mechanism determines that the memory will be recycled when it is no longer used by applications. This article studies the process of memory allocation, garbage collection mechanism, and the new API pauseforgcifcollectionimminent () in Flash Player 11 and air 3 ().

Memory Allocation

Flash Player uses the gcheap to allocate a large amount of blank storage space (Millions of bytes) from the operating system (OS)
. Then gcheap splits the large amount of storage space into smaller 4 K pages and submits these pages to the memory manager of the garbage collection mechanism (GC) as needed.


Figure 1. gcheap allocates memory from the OS, splits the memory into 4 K pages, and submits them to the GC.

Then GC uses these 4 K pages to provide memory space for medium and small objects up to 2 K in the system.


Figure 2. GC distributes 4 K pages to objects smaller than 2 K.

For objects larger than 2 k (bitmap, video, file, etc.), gcheap provides a large number of blank storage devices close to 4 K.

When almost all 4 K pages in a large block are allocated, Flash Player runs GC to recycle memory that is no longer in use before gchead tries to allocate more memory space from the OS. In other words, GC is triggered by memory allocation. Remember this in testing and Program Summary analysis, because it means that the memory usage of an idling program will never change.

Heap and stack

Heap is the memory space allocated to any created or initialized objects during the running process. Objects always exist in heap before they are recycled.


Figure 3. Object A exists in heap and is referenced by the local variable O in stack.

Stack is the memory space that stores all variables defined during the compilation period. The stack memory is mainly used in a continuous manner and reused. Push can be added to the first place of the stack, and pop is removed from the first place of the stack, the only way to insert data in the middle of the stack is to clear the top part of the position.

Local method variables, parameters, and the location information returned when a method function ends, must be pushed to the stack when the method function is running. Stack changes quickly, and its object reference time is usually very short. The object reference can exist in the stack, but the memory allocation of the object comes from heap.


Figure 4. Partial Variables are pushed to the stack when they are declared. After the method function runs, the returned location information is pushed to the stack.

Execution of the garbage collection mechanism during flash running
Flash Player and Air
The combination of a delayed reference counter and a traditional tag/cleaning device is used.

· Deferred Reference Counter

There is a reference difference between heap and stack in the deferred reference counter. Because the stack changes rapidly and often contains a short reference, the reference counter is not used in the stack reference, and the heap reference is retained and accumulated.


Figure 5. The number of times Object Tracking understands them.

Each object in heap has the number of events pointing to it. Each time a reference is created for an object, the number of references to the object increases. When you delete a reference, the number of object references is reduced. If the number of objects referenced is zero (no event points to it), the object is added to the zero computing table (zct ). When the zct is full, the stack scans the zct to find the reference from the stack to the object. All objects referenced by the stack in zct will be deleted.

One problem of delaying the reference count is loop reference. If both objecta and objectb point to the other party, but no other objects point to them in the system, then they will not have zero references and will not be selected by the garbage collection mechanism when using the reference counter. This is the usage of the mark/clear garbage collector.


Figure 6. objecta and objectb are mutually referenced, but there are no other reference parameters.

· Mark/sweep

The applications running in Flash Player or air have multiple gcroot types. You can regard gcroot as the trunk and the Application object as the branches. The stage is a gcroot and the loader is gcroot, the fixed menu is gcroot. All Program objects in use can be obtained by gcroot within the program, and gcroot will never be recycled.

All objects in the program have a "flag bit". When the mark phase of the garbage collection mechanism starts, all the mark bits are cleared. mmgc is responsible for tracking and understanding gcroot in all programs, the garbage collector starts from the root directory and outputs each object and sets the tag bit for all objects it comes into contact, objects that cannot be obtained in the root directory cannot be obtained in the program. The mark bit cannot be obtained or set in the mark stage. Once the recycler completes the mark for all the objects found, the sweep phase begins. Objects with no flag bits are deleted and their memory is recycled.


Figure 7. Objects in loop reference are not marked

Figure 7 shows that in gcroot, each object that can be obtained has its own tag bit settings (in the blue part), and the other two objects (objecta and objectb) these two objects are trapped in a loop reference and cannot be obtained by gcroot, and their tag bits cannot be set. Therefore, even if they are not zero-reference times, these two objects will be recycled.

· Weak references

Flash Player can also retain references for objects of the specified type, which is called "weak references ". Weak references are not accessible to normal tracing processes in the garbage collector (the process of finding accessible objects by tracking the root directory.

When you instantiate a new dictionary, you can specify a weak-bound dictionary field.

  1. VaR D: dictionary = New Dictionary (true );
  2. D [someobject] = somevalue;

Copy code

You can also set the useweakreference parameter of the addeventlistener () function to true when adding event listening.

  1. OBJ. addeventlistener ("type", handler, false, 0, true );

Copy code

In the preceding two paragraphs, you allow Flash Player to retain a reference in the two objects instead of retaining the reference in a weak way. In fact, this means that this special reference will not be traced during the marking process.


Figure 8. Weak references are not tracked during marking.

In this way, the unique path to objectb will be relatively weak and will not run during the tracing process. Therefore, objectb will not be marked so that it will be recycled. Then, if there are stronger paths to objectb, objectb will be marked and retained.


Figure 9. Strongly referenced objects will be found and marked during the tracking process.

When reference is no longer used, it should be cleared. You only need to use removeeventlistener () to remove entries that are no longer used on the dictionary. However, it is impractical or impossible to clear useless references. For example, if a class is instantiated and you do not know it, delete it. This is the case for the entry Renderer. In this way, in order to retain the weak references of objects, Flash Player is allowed to eventually remove them and reclaim the memory.

· Memory recycler
Mmgc is regarded as a hidden collector for marking/cleaning. mmgc cannot determine whether some amount in memory is an object pointer (memory address) or a value, to prevent unexpected collection of objects pointed to by some values, mmgc treats each value as a pointer, some objects that are not actually pointed to will never be recycled and considered as memory leaks, even if you want to reduce memory leaks for optimization, these occasional leaks produced by conservative GC occur randomly and do not change with time, and the impact on applications is much less than the developer's human leakage.

Growth recovery

Unfortunately, the garbage collection mechanism causes the Flash Player to periodically pause as the process completes, which is proportional to the amount of memory currently used by the application, it will be longer than expected and can be observed in some programs.

In the garbage collection process, the mark phase is the most intensive. Therefore, the working queue and three-color algorithm are used during the growth process, and the queue retains the marked status of the marked growth value.

Table 1. Three-color Algorithm
The black object is marked and no longer in the queue
The gray object is in the queue but has not been marked
White objects are neither marked nor in the queue

At the beginning of the Mark stage, all gcroot is put in the queue and grayed out.


Figure 10. gcroot is dimmed when it is put into the work queue.

The Mark process continues. The mark object turns black and is removed from the work queue.


Figure 11. The tag object is black and no longer in the work queue.

The process undoubtedly continues until a new (white) object is added to the black object, and then the white object no longer has the tag bit settings because their gcroot has been marked, without the flag bits, they will be recycled in the sweep phase.


Figure 12. The new object is added to the previously marked object.

To avoid this problem, the "Write barrier" in mmgc is used to prevent any white objects from being transferred to the work queue immediately when they are added to the black object.


Figure 13. The new object enters the work queue immediately when it is added to the previously marked object.

Using work queues and three-color algorithms, you can control the start and stop of the Mark stage to prevent large-scale and unnecessary pause of the garbage collection mechanism.

Strong

The Mark stage is the most intensive part of the garbage collection mechanism, but in fact it takes time to clear the garbage-allocate the released memory-and the memory allocation will also pause the application. The time required by the garbage collector to complete the mark stage and start sweep (memory allocation) is called force.


Figure 14. Force

Public static function pauseforgcifcollectionimminent (imminence: Number = 0.75): void is a new method in Flash Player 11 and air 3. It allows you to access the garbage collector, this improves the tagging process and execution collection (the API entry in the ActionScript reference document ). You can list them by time before they discover any possible pauses. This provides a better user experience. For example, a game program may call this function when completing a level, and then reduce the possibility of pause in the game process.

The pressing value you pass to this method is compared with the position of the garbage collector in the mark stage. If the value you pass is smaller than the pressing value of the recycler, Mark and sweep will be synchronized and cause program pauses. The garbage collector accounts for at least 25% of processes in progress before it detects the need to pause. Passing a smaller value (although greater than 0.25) will be more forced to recycle and cause the program to pause. Passing a larger value will make the recycler complete the recycle at any time only when it is about to happen.

Start from here

Understanding how the Memory Manager and garbage collection mechanism in Flash Player and air work can help you optimize your code and develop applications with better results. Check Michael labriola's report on the garbage collection mechanism, talking trash. Read Christian Cantrell's providing hints to the garbage collector in air 3. You can also take a look at the detailed discussion of mmgc, which includes some descriptions of the basic C ++ code.

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.